天天看點

celery 在Python django項目中的使用

**

celery 在Python django項目中的使用

**

安裝依賴:(中間人broker使用redis,也可使用RabbitMQ) 本問使用redis

pip install redis

pip install celery

pip install celery-with-redis

安裝redis并啟動 略: 安裝redis

第一步,在django項目的settings.py 中配置celery 相關:

# 配置celery資訊

BROKER_URL = ‘redis://localhost:6379/0’

# 配置使用者存儲結果

CELERY_RESULT_BACKEND = ‘redis://localhost:6379/0’

# 連接配接逾時

BROKER_TRANSPORT_OPRIONS = {‘visibility_time’: 3600}

# 消息格式

CELERY_ACCEPT_CONNECT = [‘APPLICATION/JSON’, ]

CELERY_TASK_SERIALIZER = ‘json’

CELERY_RESULT_SERIALIZER = ‘json’

# celery 時區

CELERY_TIMEZONE = TIME_ZONE

celery 在Python django項目中的使用

第二步: 在與 項目名稱相同的app下建立celery.py檔案(将settings中的配置應用到app)

A:編輯 celery.py

import os

from celery import Celery

project_name = os.path.split(os.path.abspath(’.’))[-1] # 項目名稱

project_settings = ‘%s.settings’ % project_name

# 設定環境變量

os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, project_settings)

# 執行個體化celery

app = Celery(project_name)

# 使用django的配置檔案進行配置

app.config_from_object(‘django.conf:settings’)

B:在項目同名的檔案夾的 init.py 檔案中添加:

from future import absolute_import, unicode_literals

‘’’

absolute_import 如果目前目錄下的函數與系統中的有重複,優先調用目前目錄下的

‘’’

from .celery import app as celery_app

**第三步:在  項目 app中建立task.py  寫入需要異步執行的邏輯;使用celery中的shared_task作為裝飾器來
執行異步排程**
	@shared_task
	def  __():
		pass
           

第四步: 調用 task.py 中的函數。使用: 函數名.delay() (啟動異步排程)

第五步:啟動 celery

celery -A 項目名稱 worker -l info

celery 在Python django項目中的使用

親測有效