2013-11-23 2 views
33

간단한 장고 예제를 보겠습니다.셀러리와 장고 간단한 예제

응용 프로그램/models.py

from django.db import models 
from django.contrib.auth.models import User 

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    token = models.CharField(max_length=32) 

응용 프로그램/views.py

from django.http import HttpResponse 
from django.views.decorators.csrf import csrf_exempt 
from forms import RegisterForm 
from utils.utilities import create_user 

@csrf_exempt 
def register_view(request): 
    if request.method == 'POST': 
     form = RegisterForm(request.POST) 
     if form.is_valid(): 
      create_user(form.cleaned_data) 
      return HttpResponse('success') 

유틸/utilities.py

def create_user(data): 
    user = User.objects.create_user(username=data['username'], email=None, password=data['password']) 
    user.save() 
    profile = UserProfile() 
    profile.user = user 
    profile.token = generate_token() 
    profile.save() 

사람이 예제 셀러리의 구현을 제공 할 수 ? 이 프로젝트가 초당 수백 건의 대규모 프로젝트라고 상상해보십시오. 당신을 가정

+1

예제에 대한 직접적인 요청은 이전의 연구를 수행하지 않은 사람들에게서 자주 왔기 때문에 주제를 벗어난 것으로 간주되는 경향이 있습니다. 그건 분명히 당신에게 적용되지 않지만, 일반적인 지침을 알고있을 가치가 있습니다 - 당신이 할 때 [도움말] (http://stackoverflow.com/help) 섹션을 참조하십시오. – halfer

답변

76

는이 두 파이썬의 celery 설치 django-celery 앱에서 다음 tasks.py 파일 생성 : 위의 예에서 utils/utilities.py 파일을 삭제

유틸/

from celery import task 
# other imports 

@task() 
def create_user(data): 
    user = User.objects.create_user(
     username=data['username'], email=None, password=data['password'] 
    ) 
    user.save() 
    profile = UserProfile() 
    profile.user = user 
    profile.token = generate_token() 
    profile.save() 

    return None 

tasks.py합니다. views.py 변화에 코드에서

create_user 호출에서 :

create_user(form.cleaned_data) 

에 : 기본적으로

create_user.delay(form.cleaned_data) 

create_user은 지금 셀러리 작업입니다; 파이썬 패키지가 이미 설치되어 있다면 (위와 같이), 코드 와이즈 (요구 사항을 구현 한 것)가 그 것이다. delay은 비동기 적으로 함수를 실행합니다. 즉, 비동기 작업이 완료 될 때까지 기다리지 않고 HTTP 응답이 반환됩니다.

로컬에서는 python manage.py celeryd을 사용하여 셀러리 데몬 프로세스를 실행할 수 있습니다.

프로덕션 환경에서는 upstart, supervisor 또는 이러한 프로세스의 수명주기를 제어하는 ​​기타 도구를 사용하여 셀러리 프로세스 자체를 설정해야합니다.

자세한 내용은 here에 설명되어 있습니다.

+0

나는 이것을 위해 황금 배지를 줄 것이다! 정말 고마워! –

+0

@TeodorScorpan 감사합니다 :) –

+2

장고 관리자에서 나타나는 작업을 얻으려고 몇 시간을 보낸 후이 장고 - 셀러리 템플릿 프로젝트 않았다 : https://github.com/mikeumus/django-celery-example 희망 누군가가 도움이되기를 바랍니다. ! :) – Mikeumus