바뀜

둘러보기로 가기 검색하러 가기
2,480 바이트 추가됨 ,  2023년 1월 6일 (금) 18:28
새 문서: == 개요 == 장고 내에서 셀러리를 사용하기 위한 정보를 담은 문서. === 운용방식 === 메시지 브로커라는 외부 서버를 사용하여 작업을 수행...
== 개요 ==
장고 내에서 셀러리를 사용하기 위한 정보를 담은 문서.

=== 운용방식 ===
메시지 브로커라는 외부 서버를 사용하여 작업을 수행한다.(보통 Redis나 RabbitMQ)

이 메시지 브로커가 셀러리에 feed를 넘긴다.

즉, 장고가 파이썬 함수를 실행하면 셀러리가 해당 작업을 큐에 올린다. 샐러리는 이를 다시 메시지브로커에.(장고는 다른 작업을 지속할 수 있도록) 작업 결과는 셀러리로 돌아온다.

== 기초 사용법 ==
사람마다 사용하는 방식이 다르다.
{| class="wikitable"
!과정
!설명
!방법
|-
|라이브러리 인스턴스 만들기
|settings.py가 있는 디렉토리에 celery.py를 생성 우측과 같이 입력한다.
|<syntaxhighlight lang="python">
from __future__ import absolute_import, unicode_literals

import os

from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_tutorial.settings')

app = Celery('celery_tutorial')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks() # 선택사항. 자동으로 하위 앱의 task.py를 탐색한다.
</syntaxhighlight>
|-
|장고가 시작될 때 자동실행
|자동실행을 위해 settings.py가 있는 디렉토리에 __init__.py를 만든다.
|<syntaxhighlight lang="python">
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',) # 샐러리
</syntaxhighlight>
|-
|settings.py 설정
|메시지브로커 주소 등 설정값을 넣어준다.
|<syntaxhighlight lang="python">
CELERY_BROKER_URL = 'redis://localhost:6379' # redis 주소값
</syntaxhighlight>
|-
|task 등록
|일을 등록한다.
위에서 app.autodiscover_tasks()를 사용했다면 각 앱의 task.py 안에 넣어주면 작동한다.
|@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
|-
|샐러리 실행
|
|celery -A settings.py가있는폴더.celery worker --loglevel=info
|}

둘러보기 메뉴