Django 作為后端Web開發框架,有時候我們需要用到定時任務來或者固定頻次的任務來執行某段代碼,這時我們就要用到Celery了。Django中有一個中間件:Django-celery
環境:
Python 3.6 Django為小于1.8版本 Celery為3.1版本第一步安裝:django-celery
pip install django-celery
第二步:配置celery和任務
創建測試django環境:
django-admin.py createproject testdjango-admin.py startapp demo
創建好的項目布局如下:
- proj/ - manage.py - proj/ - __init__.py - celery.py - settings.py - urls.py - demo/ - migrations - __init__.py - admin.py - apps.py - models.py - tasks.py - tests.py - views.py
2.1 配置celery.py文件
需要替換的內容,我都在對應的行后提示了,剩下的內容默認就好
創建test/test/celery.py文件,內容如下:
from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celery # set the default Django settings module for the 'celery' program.os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') # “proj.settings”替換為你的項目信息:test.settings app = Celery('proj') # 這里的proj替換為你的項目名稱:test # Using a string here means the worker doesn't have to serialize# the configuration object to child processes.# - namespace='CELERY' means all celery-related configuration keys# should have a `CELERY_` prefix.app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs.app.autodiscover_tasks() @app.task(bind=True)def debug_task(self): print('Request: {0!r}'.format(self.request))2.2 配置項目的init.py中配置celery內容
打開test/test/__init_.py文件,添加內容:
from __future__ import absolute_import, unicode_literals # 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 __all__ = ('celery_app',)2.3 在task.py中添加計劃任務
編輯test/demo/task.py文件,添加計劃任務,內容如下:
# Create your tasks herefrom __future__ import absolute_import, unicode_literalsfrom celery import shared_task @shared_taskdef add(x, y): return x + y @shared_taskdef mul(x, y): return x * y @shared_taskdef xsum(numbers): return sum(numbers)
第三步:任務執行
運行django項目: python manage.py runserver
3.1 后臺添加計劃任務
訪問“http://localhost:8000/admin/”,在celery的管理頁面里,選擇Periodic tasks,進行任務添加。選擇對應的任務,設置定時或者周期時間
3.2 啟動定時的celery服務
新聞熱點
疑難解答