django+django-celery+celery的整合實戰

django+django-celery+celery的整合

本篇文章主要是由於計劃使用django寫一個計劃任務出來,可以定時的輪換值班人員名稱或者定時執行腳本等功能,百度無數坑之後,終於可以湊合把這套東西部署上。本人英文不好,英文好或者希望深入學習或使用的人,建議去參考官方文檔,而且本篇的記錄不一定正確,僅僅實現crontab 的功能而已。
希望深入學習的人可以參考http://docs.jinkan.org/docs/celery/
首先簡單介紹一下,Celery 是一個強大的分佈式任務隊列,它可以讓任務的執行完全脫離主程序,甚至可以被分配到其他主機上運行。我們通常使用它來實現異步任務(async task)和定時任務(crontab)。它的架構組成如下圖
這裏寫圖片描述

可以看到,Celery 主要包含以下幾個模塊:

任務模塊 Task

包含異步任務和定時任務。其中,異步任務通常在業務邏輯中被觸發併發往任務隊列,而定時任務由 Celery Beat 進程週期性地將任務發往任務隊列。

消息中間件 Broker

Broker,即爲任務調度隊列,接收任務生產者發來的消息(即任務),將任務存入隊列。Celery 本身不提供隊列服務,官方推薦使用 RabbitMQ 和 Redis 等。

任務執行單元 Worker

Worker 是執行任務的處理單元,它實時監控消息隊列,獲取隊列中調度的任務,並執行它。

任務結果存儲 Backend

Backend 用於存儲任務的執行結果,以供查詢。同消息中間件一樣,存儲也可使用 RabbitMQ, Redis 和 MongoDB 等。

異步任務
使用 Celery 實現異步任務主要包含三個步驟:

創建一個 Celery 實例
啓動 Celery Worker
應用程序調用異步任務

一、快速入門

本地環境:

OS:centOS6.5
django-1.9
python-2.7.11
celery==3.1.20
django-celery

python、pip、django相關安裝不在詳寫,直接參考百度即可;

pip install django==1.9     安裝django 
pip install celery==3.1.20  安裝celery
pip install django-celery   安裝django-celery

安裝如果有失敗,所需要的依賴環境自行解決。例如:mysql-python等;
使用做redis作爲消息中間件,安裝redis:

二、創建django項目開始測試

1、創建django 工程 命名爲djtest

django-admin.py startproject djtest1

2、創建app 命名爲apps

cd djtest
python manage.py startapp apps1

3、創建完成後,django 目錄結構如下:
djtest1
├── apps1
│ ├── admin.py
│ ├── apps.py
│ ├── init.py
│ ├── migrations
│ │ └── init.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── djtest1
│ ├── init.py
│ ├── init.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ └── wsgi.py
└── manage.py

4、修改setting.py django配置文件,增加如下:

import djcelery  ###
djcelery.setup_loader()  ###
CELERY_TIMEZONE='Asia/Shanghai'  #並沒有北京時區,與下面TIME_ZONE應該一致
BROKER_URL='redis://192.168.217.77:16379/8'  #任何可用的redis都可以,不一定要在django server運行的主機上
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'  ###

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'djcelery',    ### 加入djcelery應用
    'apps1',     ###     加入新創建的apps1
)
TIME_ZONE='Asia/Shanghai'  ### 

開頭增加如上配置文件,根據實際情況配置redis的地址和端口,時區一定要設置爲Asia/Shanghai。否則時間不準確回影響定時任務的運行。

上面代碼首先導出djcelery模塊,並調用setup_loader方法加載有關配置;注意配置時區,不然默認使用UTC時間會比東八區慢8個小時。其中INSTALLED_APPS末尾添加兩項,分別表示添加celery服務和自己定義的apps服務。

5、編寫celery文件:djtest/djtest/celery.py

#!/bin/python
from __future__ import absolute_import

import os

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djtest1.settings')
#Specifying the settings here means the celery command line program will know where your Django project is. 
#This statement must always appear before the app instance is created, which is what we do next: 
from django.conf import settings

app = Celery('djtest1')

app.config_from_object('django.conf:settings')
#This means that you don’t have to use multiple configuration files, and instead configure Celery directly from the Django settings.
#You can pass the object directly here, but using a string is better since then the worker doesn’t have to serialize the object.

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
#With the line above Celery will automatically discover tasks in reusable apps if you define all tasks in a separate tasks.py module.
#The tasks.py should be in dir which is added to INSTALLED_APP in settings.py. 
#So you do not have to manually add the individual modules to the CELERY_IMPORT in settings.py.

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))  #dumps its own request information

6、修改djtest1/djtest1/init.py

#!/bin/python
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

7、接下來編寫你希望django去完成的app,本文中要編寫的就是在INSTALLED_APPS中註冊的apps。在celery.py中設定了對settings.py中INSTALLED_APPS做autodiscover_tasks,本文希望apps中能夠接受這樣的目錄組織:所有的app都可以放到apps下面,而且每個app都有獨立的目錄,就和上面的app1、app2一樣,每個app各自有各自的init.py和tasks.py(注意,每個app都需要init.py文件,可以是空白的)。但是這樣的結構組織在啓動時會報錯說module apps找不到。然後在apps下增加了一個init.py文件,這時報錯沒了,但是apps下每個app的tasks.py中的任務函數還是無法被django和celery worker找到。

**然後嘗試了在apps1下面寫一個__init__.py(空白)和task.py,所有的task function都寫到tasks.py中,如下**
from __future__ import absolute_import

from celery import task

from celery import shared_task

#from celery.task import tasks 
#from celery.task import Task 

@task()
#@shared_task
def add(x, y):
    print "%d + %d = %d"%(x,y,x+y)
    return x+y
#class AddClass(Task):
#    def run(x,y):
#        print "%d + %d = %d"%(x,y,x+y)
#        return x+y
#tasks.register(AddClass)

@shared_task
def mul(x, y):
    print "%d * %d = %d"%(x,y,x*y)
    return x*y

@shared_task
def sub(x, y):
    print "%d - %d = %d"%(x,y,x-y)
    return x-y

8、同步數據庫

python manage.py makemigrations

python manage.py migrate

9、創建超級用戶

python manage.py createsuperuser

Username (leave blank to use 'work'): admin
Email address: [email protected]
Password: 
Password (again): 
Superuser created successfully.

10、啓動django-web、啓動celery beat 啓動 celery worker進程

python manage.py runserver 0.0.0.0:8001#啓動django的應用,可以動態的使用django-admin來管理任務

python manage.py celery beat #應該是用來監控任務變化的

python manage.py  celery worker -c 6 -l debug  #任務執行進程,worker進程

11、通過django-admin添加已註冊的任務,並查看輸出是否正常。

http://192.168.217.77:8001/admin/ 輸入密碼登錄
(1)
登錄後添加任務:
這裏寫圖片描述
點擊紅線標記的列表,通過add來添加;
(2)
這裏寫圖片描述

點擊進入以後,可以看到已經存在的任務,點擊添加即可;
(3)
這裏寫圖片描述
按照提示,輸入name,通過task(registered) 選擇已經註冊的函數服務。
選擇運行模式,阻塞模式,爲多長時間間隔運行一次,或者crontab形式運行。
點擊Arguments(show),添加需要傳入註冊函數的參數。
(4)
這裏寫圖片描述
實例,具體名稱以及運行時間以及傳入參數等。
(5)
這裏寫圖片描述
保存之後,可以查看到列表。

(6)在python manage.py celery worker -c 6 -l debug啓動的窗口可以看到如下的運行過程,證明已經生效。
這裏寫圖片描述

第一行紅色標記,可以看到註冊函數被調用,第二行紅色標記,可以看到函數的返回值。

到此已經基本完成。在實際運用中,我們只需要修改或者添加到tasks.py文件裏一些函數,讓他註冊到裏邊。我們從前臺django-web寫入任務,可以使其動態加載到任務。並且把正確的參數傳過去,就可以正常執行。完成我們所想要的通過這個django-celery工具製作定期的備份、統一管理的crontab平臺等。

參考文章:

http://blog.csdn.net/vintage_1/article/details/47664297
http://docs.jinkan.org/docs/celery/getting-started/introduction.html
http://www.jianshu.com/p/f78ed01969b3
http://www.jianshu.com/p/b7f843f21c46
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章