django之使用celery-把耗時程序放到celery里面執(zhí)行的方法
1 在虛擬環(huán)境創(chuàng)建項目test和應(yīng)用booktest(過程省略),然后安裝所需的包
pip install celery==3.1.25 pip install celery-with-redis==3.0 pip install django-redis==3.1.17
2 配置settings,
# 數(shù)據(jù)庫使用mysql
DATABASES = {
'default': {
'ENGINE':'django.db.backends.mysql',
'NAME':'test',
'USER':'root',
'PASSWORD':'mysql',
'HOST':'localhost',
'PORT':3306,
}
}
# 注冊djcelery應(yīng)用
INSTALLED_APPS = (
...
'djcelery',
)
# celery配置
# 如報錯 ImportError: No module named djcelery ,是因為沒有在虛擬環(huán)境運(yùn)行導(dǎo)致, workon h1進(jìn)入虛擬環(huán)境再運(yùn)行解決
import djcelery
# 初始化所有的task任務(wù),這些任務(wù)來自booktest.task模塊
djcelery.setup_loader()
# 使用redis第0個數(shù)據(jù)庫,并綁定ip端口
BROKER_URL='redis://127.0.0.1:6379/0'
# 設(shè)置初始化的任務(wù)來源
CELERY_IMPORTS = 'booktest.task'
3 在應(yīng)用目錄booktest下面創(chuàng)建任務(wù)列表文件task.py
from celery import task
import time
# 加上@task裝飾器,則python函數(shù)就變成一個celery任務(wù)
@task
def celery_test():
print('hello...')
time.sleep(5)
print('world...')
4 創(chuàng)建視圖,并配置相關(guān)的url配置,把耗時任務(wù)放入視圖被調(diào)用
# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from task import celery_test
# celery練習(xí)1:把耗時程序放在celery中執(zhí)行
def celerytest(request):
# function.delay(參數(shù)),celery任務(wù)celery_test調(diào)用方法
celery_test.delay()
return HttpResponse('ok')
# 根級url配置 test.urls
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^celery/', include('booktest.urls')),
]
# 應(yīng)用下的url配置?。鈕oktest.urls
from django.conf.urls import url
import views
urlpatterns=[
url(r'^celerytest/$', views.celerytest)
]
5 遷移,生成celery所需的數(shù)據(jù)表
python manage.py migrate
6 啟動redis
sudo redis-server /etc/redis/redis.conf
7 啟動worker
python manage.py celery worker --loglevel=info
8 另開一個終端窗口,啟動django服務(wù)器
python manage.py runserver
9 測試,輸入url,如 http://127.0.0.1:8000/celery/celerytest/,則返回'ok'
同時,會在worker對應(yīng)的窗口看到耗時任務(wù)程序在此輸出,即當(dāng)用戶請求時,不用等待太久就可以得到結(jié)果'ok',同時耗時任務(wù)程序也被異步執(zhí)行,提高用戶體驗.
以上這篇django之使用celery-把耗時程序放到celery里面執(zhí)行的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python面向?qū)ο蟪绦蛟O(shè)計之繼承、多態(tài)原理與用法詳解
這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計之繼承、多態(tài),結(jié)合實例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計中繼承、多態(tài)的相關(guān)概念、原理、用法及操作注意事項,需要的朋友可以參考下2020-03-03
Python實現(xiàn)視頻轉(zhuǎn)換為字符畫詳解
這篇文章主要介紹了如何通過Python實現(xiàn)讀取視頻并將其轉(zhuǎn)換為字符畫的示例代碼,文中講解詳細(xì),對我們的學(xué)習(xí)和工作有一點的價值,感興趣的小伙伴可以了解一下2021-12-12
Python計算三角函數(shù)之a(chǎn)sin()方法的使用
這篇文章主要介紹了Python計算三角函數(shù)之a(chǎn)sin()方法的使用,是Python入門的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
python 將字符串轉(zhuǎn)換成字典dict的各種方式總結(jié)
下面小編就為大家分享一篇python 將字符串轉(zhuǎn)換成字典dict的各種方式總結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

