"Celery:Django"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
(새 문서: == 개요 == 장고 내에서 셀러리를 사용하기 위한 정보를 담은 문서. === 운용방식 === 메시지 브로커라는 외부 서버를 사용하여 작업을 수행...) |
(차이 없음)
|
2023년 1월 6일 (금) 18:28 판
1 개요
장고 내에서 셀러리를 사용하기 위한 정보를 담은 문서.
1.1 운용방식
메시지 브로커라는 외부 서버를 사용하여 작업을 수행한다.(보통 Redis나 RabbitMQ)
이 메시지 브로커가 셀러리에 feed를 넘긴다.
즉, 장고가 파이썬 함수를 실행하면 셀러리가 해당 작업을 큐에 올린다. 샐러리는 이를 다시 메시지브로커에.(장고는 다른 작업을 지속할 수 있도록) 작업 결과는 셀러리로 돌아온다.
2 기초 사용법
사람마다 사용하는 방식이 다르다.
과정 | 설명 | 방법 |
---|---|---|
라이브러리 인스턴스 만들기 | settings.py가 있는 디렉토리에 celery.py를 생성 우측과 같이 입력한다. | 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를 탐색한다.
|
장고가 시작될 때 자동실행 | 자동실행을 위해 settings.py가 있는 디렉토리에 __init__.py를 만든다. | 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',) # 샐러리
|
settings.py 설정 | 메시지브로커 주소 등 설정값을 넣어준다. | CELERY_BROKER_URL = 'redis://localhost:6379' # redis 주소값
|
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 |