Django異步任務(wù)之Celery的基本使用
Celery
許多Django應(yīng)用需要執(zhí)行異步任務(wù), 以便不耽誤http request的執(zhí)行. 我們也可以選擇許多方法來完成異步任務(wù), 使用Celery是一個比較好的選擇, 因為Celery有著大量的社區(qū)支持, 能夠完美的擴展, 和Django結(jié)合的也很好. Celery不僅能在Django中使用, 還能在其他地方被大量的使用. 因此一旦學(xué)會使用Celery, 我們可以很方便的在其他項目中使用它.
celery 是一個用于實現(xiàn)異步任務(wù)的庫, 在很多項目中都使用它, 它和 django 融合使用很完美. 使用 celery 可以在實現(xiàn) http request請求返回 view 前做一些我們想做的而且耗時的事情而不會讓用戶等待太久
環(huán)境
django 版本 == 1.11.6
celery 版本 == 3.1.25
安裝
pip install django-celery pip install celery
首先需要將 celery 添加到 django 項目的 settings 里, celery 任務(wù)和 django 需要一個 中間人(broker),,這里使用的是 django 自帶的 broker, 但在生產(chǎn)中一般使用 rabbitmq, Redis 等,在 INSTALLED_APP 中需要添加 djcelery 和 kombu.transport.django, 還有 app 應(yīng)用。
- project/project/ settings.py:
import djcelery djcelery.setup_loader() BROKER_URL = 'django://' INSTALLED_APP = ( ... 'app' 'djcelery', 'kombu.transport.django', )
新建 celery.py 創(chuàng)建一個 celery 應(yīng)用,并添加以下內(nèi)容
- project/project/ celery.py:
# 相對路徑導(dǎo)入, 防止導(dǎo)入 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') # 創(chuàng)建一個 celery 應(yīng)用 app = Celery('project') # 導(dǎo)入配置 app.config_from_object('django.conf:settings') # 自動發(fā)現(xiàn) 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:
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 中添加任務(wù),文件名必須是 tasks.py, 在普通 python 函數(shù)前加一個 @task() 裝飾器就變成了 celery task
-project/app/ tasks.py:
from celery.task import task from time import sleep @task() def helloWorld(): print 'helloWorld' sleep(10) print 'helloWorld' return 'helloCelery'
這樣,一個任務(wù)就創(chuàng)建成功了,只剩下在 view 中調(diào)用了
-project/app view.py:
from tasks.py import helloWorld def home(): helloWorld.delay() return HttpResponse('helloCelery')
最后
python manage.py migrate
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
Python+Matplotlib+LaTeX玩轉(zhuǎn)數(shù)學(xué)公式
這篇文章主要為大家介紹了如何在Matplotlib中使用LaTeX?公式和符號以及Python如何生成LaTeX數(shù)學(xué)公式。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-02-02TensorFlow keras卷積神經(jīng)網(wǎng)絡(luò) 添加L2正則化方式
這篇文章主要介紹了TensorFlow keras卷積神經(jīng)網(wǎng)絡(luò) 添加L2正則化方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05在python中計算ssim的方法(與Matlab結(jié)果一致)
這篇文章主要介紹了在python中計算ssim的方法(與Matlab結(jié)果一致),本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12python 解決動態(tài)的定義變量名,并給其賦值的方法(大數(shù)據(jù)處理)
今天小編就為大家分享一篇python 解決動態(tài)的定義變量名,并給其賦值的方法(大數(shù)據(jù)處理),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11