Django異步任務之Celery

Celery

celery 是一個用於實現異步任務的庫, 在不少項目中都使用它, 它和 django 融合使用很完美. 使用 celery 能夠在實現 http request請求返回 view 前作一些咱們想作的並且耗時的事情而不會讓用戶等待過久python

環境

django 版本 == 1.11.6django

celery 版本 == 3.1.25app

安裝

pip install django-celery
pip install celery

 

首先須要將 celery 添加到 django 項目的 settings 裏, celery 任務和 django 須要一個 中間人(broker),,這裏使用的是 django 自帶的 broker, 但在生產中通常使用 rabbitmq, Redis 等,在 INSTALLED_APP 中須要添加 djcelery 和 kombu.transport.django, 還有 app 應用。異步

- project/project/ settings.py:函數

import djcelery

djcelery.setup_loader() 
BROKER_URL = 'django://'

INSTALLED_APP = (
    ...
    'app'
    'djcelery',
    'kombu.transport.django',
)

新建 celery.py 建立一個 celery 應用,並添加如下內容this

- project/project/ celery.py:spa

# 相對路徑導入, 防止導入 celery 時衝突
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# 讓 celery 能找到 django 項目
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
# 建立一個 celery 應用
app = Celery('project')

# 導入配置
app.config_from_object('django.conf:settings')
# 自動發現 task
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):

    print('Request: {0!r}'.format(self.request))

- project/project/ __init__.py:debug

from __future__ import absolute_import

# 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

在 django app 中添加任務,文件名必須是 tasks.py, 在普通 python 函數前加一個 @task() 裝飾器就變成了 celery taskcode

project/app/ tasks.py:orm

from celery.task import task
from time import sleep

@task()
def helloWorld():
    print 'helloWorld'
    sleep(10)
    print 'helloWorld'
    return 'helloCelery'

這樣,一個任務就建立成功了,只剩下在 view 中調用了

project/app view.py:

from tasks.py import helloWorld

def home():

    helloWorld.delay()

    return HttpResponse('helloCelery')

最後

python manage.py migrate
相關文章
相關標籤/搜索