Django初步使用Celery處理耗時任務(wù)和定時任務(wù)問題
Celery是Python開發(fā)分布式任務(wù)列隊的處理庫??梢援惒椒植际降禺惒教幚砣蝿?wù),也可定時執(zhí)行任務(wù)等等。
通常我們可以使用celery在Django執(zhí)行一些比較耗時的任務(wù)(例如發(fā)郵件)和后臺任務(wù)(例如爬蟲和更新服務(wù)器緩存)。
在Django中使用有兩種方式:
- 1)使用django-celery應(yīng)用
- 2)直接使用Celery
1、Celery方式的選擇
這里Celery的中間人,采用Redis。也可以用Django自身的mongodb等。Celery的中間人你可以理解為在Celery執(zhí)行過程中的數(shù)據(jù)支持。保存列隊記錄、執(zhí)行記錄等等。
需要安裝celery-with-redis,執(zhí)行命令
pip?install?celery-with-redis
該命令會自動安裝redis(python庫操作redis的庫)、celery、kombu、billiard、amqp、vine和celery-with-redis相關(guān)庫。
注意,這里pip安裝的redis是python操作redis的庫,非redis數(shù)據(jù)庫。
redis數(shù)據(jù)庫需要獨立安裝,在cmd里輸入 pip3 install redis
先說說django-celery的方式吧。這種方式就是通過manage.py啟動celery。通常先被提到的方案是不會采用。用pip安裝django-celery,在settings引用djcelery應(yīng)用。
再更新數(shù)據(jù)庫:
python manage.py makemigrations djcelery python manage.py migrate djcelery
查看數(shù)據(jù)庫,會發(fā)現(xiàn)多了很多相關(guān)的表,顯得十分多余了就。
djcelery還有個用途是在admin后臺動態(tài)添加定時任務(wù)。這個功能也是比較雞肋,維護不方便而且可能造成各種不可預(yù)知的問題。
所以建議直接使用Celery管理Django中的任務(wù)(第二種方式)。這種方式也是Celery官網(wǎng)推薦的方式。
2、Django簡單項目準(zhǔn)備
這里我也簡單做一個示例。
首先,確保celery和redis已經(jīng)安裝好了,并且已經(jīng)啟動了Redis服務(wù)。
另外,有個已經(jīng)搭建好了Django項目。
作為示例,簡單project和簡單app如下:

左邊側(cè)邊欄是該django的目錄結(jié)構(gòu),右邊是myapp中的Blog模型。
再進入后臺隨便加了兩條數(shù)據(jù):

為了測試,一切從簡。views.py寫了一個響應(yīng)方法:
#views.py
from django.shortcuts import render
from django.http import HttpResponse
from models import Blog
import json
def home(request):
data = list(Blog.objects.values('caption'))
return HttpResponse(json.dumps(data), content_type = 'application/json')django項目的urls.py加了一條首頁的url路由設(shè)置:
#urls.py
from django.conf.urls import url
from django.contrib import admin
from myapp.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', 'myapp.views.home', name='home')
]運行django項目:
python?manage.py?runserver
打開http://localhost:8000/,如下效果:

3、Django加入Celery
現(xiàn)打開首頁要執(zhí)行一個收集訪客數(shù)據(jù),發(fā)送郵件等操作。這是一個耗時任務(wù),若放在home處理方法中執(zhí)行,用戶打開首頁會很慢。用戶體驗不好,很可能不會等到頁面打開。
通常這個耗時任務(wù)可以多線程處理或者異步處理。我們模擬一個耗時任務(wù),丟給Celery異步處理。
先模擬耗時任務(wù),打開views.py,修改如下:
#views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Blog
import json
import time
def sendmail(email):
print('start send email to %s' % email)
time.sleep(5) #休息5秒
print('success')
return True
def home(request):
#耗時任務(wù),發(fā)送郵件
sendmail('test@test.com')
#其他行為
data = list(Blog.objects.values('caption'))
return HttpResponse(json.dumps(data), content_type = 'application/json')如此一來,至少需要再多等待5秒,才可以打開網(wǎng)頁。
打開settings.py所在的文件夾,新建celery.py文件。
加入如下代碼(注意,因為celery-with-django版本限制,我安裝的celery版本為3.1.25??赡躢elery4.x的版本代碼不同):
#celery.py
from __future__ import absolute_import, unicode_literals
from celery import Celery
from django.conf import settings
import os
#獲取當(dāng)前文件夾名,即為該Django的項目名
project_name = os.path.split(os.path.abspath('.'))[-1]
project_settings = '{}.settings'.format(project_name)
#設(shè)置環(huán)境變量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings)
#實例化Celery
app = Celery(project_name)
#使用django的settings文件配置celery
app.config_from_object('django.conf:settings')
#Celery加載所有注冊的應(yīng)用
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)這個文件還沒被加載,接著打開settings.py同個目錄下的__init__.py文件。讓運行該Django項目的時候,加載該文件配置Celery。
修改代碼如下:
#__init__.py from __future__ import absolute_import, unicode_literals #引入celery實例對象 from .celery import app as celery_app
還需在settings.py中設(shè)置celery,尤其是中間人的設(shè)置。若不設(shè)置中間人,會提示無法連接中間人的錯誤。
在settings.py文件中添加如下設(shè)置:
#celery settings #celery中間人 redis://redis服務(wù)所在的ip地址:端口/數(shù)據(jù)庫號 BROKER_URL = 'redis://localhost:6379/0' #celery結(jié)果返回,可用于跟蹤結(jié)果 CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' #celery內(nèi)容等消息的格式設(shè)置 CELERY_ACCEPT_CONTENT = ['application/json',] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' #celery時區(qū)設(shè)置,使用settings中TIME_ZONE同樣的時區(qū) CELERY_TIMEZONE = TIME_ZONE
4、把耗時任務(wù)丟給celery處理
上面views.py中有個耗時任務(wù)sendmail。在myapp應(yīng)用中新建文件tasks.py,將sendmail方法剪切到該文件中并用定義為celery任務(wù)。
tasks.py文件如下代碼:
#tasks.py
from celery.decorators import task
import time
@task
def sendmail(email):
print('start send email to %s' % email)
time.sleep(5) #休息5秒
print('success')
return True在原有的方法上加上celery裝飾器task(或者也可以通過前面添加的celery_app給sendmail方法加裝飾器):
#tasks.py
#myproject是當(dāng)前django的項目名
from myproject import celery_app
import time
@celery_app.task
def sendmail(email):
print('start send email to %s' % email)
time.sleep(5) #休息5秒
print('success')
return True另外原先的views.py修改如下:
#views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Blog
from .tasks import sendmail #引用tasks.py文件的中sendmail方法
import json
def home(request):
#耗時任務(wù),發(fā)送郵件(用delay執(zhí)行方法)
sendmail.delay('test@test.com')
#其他行為
data = list(Blog.objects.values('caption'))
return HttpResponse(json.dumps(data), content_type = 'application/json')5、本地啟動celery并測試
啟動celery之前,確保已經(jīng)安裝redis和啟動redis服務(wù)。
本地開發(fā)環(huán)境運行redis-cli看是否可以正常連接,若不行,再手工執(zhí)行redis-server命令并保持窗口即可。

接著,啟動celery worker。這個worker是用于異步執(zhí)行任務(wù)的“工作者”。
進入manage.py文件所在的目錄,執(zhí)行如下命令:
Celery?-A?myproject?worker?-l?info
出現(xiàn)如下窗口和消息,則正常執(zhí)行。

celery worker會掃描django項目中有哪些task任務(wù),并加入進來。見上圖的藍色字下[tasks]字樣。
最后,再啟動django服務(wù)器。這個大家熟悉的python manage.py runserver。
打開首頁,可以發(fā)現(xiàn)沒有5秒等待立即得到首頁內(nèi)容。查看celery worker,可看到執(zhí)行sendmail方法的消息。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python2和python3實現(xiàn)在圖片上加漢字的方法
python2和python3實現(xiàn)在圖片上加漢字,最主要的區(qū)別還是內(nèi)部編碼方式不一樣導(dǎo)致的,在代碼上表現(xiàn)為些許的差別。這篇文章主要介紹了python2和python3實現(xiàn)在圖片上加漢字,需要的朋友可以參考下2019-08-08
詳解python實現(xiàn)可視化的MD5、sha256哈希加密小工具
這篇文章主要介紹了詳解python實現(xiàn)可視化的MD5、sha256哈希加密小工具,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
pygame游戲之旅 調(diào)用按鈕實現(xiàn)游戲開始功能
這篇文章主要為大家詳細(xì)介紹了pygame游戲之旅的第12篇,教大家調(diào)用按鈕實現(xiàn)游戲開始功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11
使用Python實現(xiàn)從各個子文件夾中復(fù)制指定文件的方法
今天小編就為大家分享一篇使用Python實現(xiàn)從各個子文件夾中復(fù)制指定文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
python使用OS模塊操作系統(tǒng)接口及常用功能詳解
os是?Python?標(biāo)準(zhǔn)庫中的一個模塊,提供了與操作系統(tǒng)交互的功能,在本節(jié)中,我們將介紹os模塊的一些常用功能,并通過實例代碼詳細(xì)講解每個知識點2023-06-06
Python 實現(xiàn)數(shù)據(jù)結(jié)構(gòu)中的的棧隊列
這篇文章主要介紹了Python 實現(xiàn)數(shù)據(jù)結(jié)構(gòu)中的的棧,隊列,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05

