django+celery實現非同步訊息佇列
阿新 • • 發佈:2019-01-29
步驟:1. 建立專案 django-admin startproject project2. 建立apppython manage.py startapp sendemail3. 配置settings.py
5.初始化資料庫python manage.py makemigrationspython manage.py migrate 6. 配置我們的celery-beatdjango提供了一個視覺化的後臺,啟動服務 python manage.py runserver 。瀏覽器訪問 :120.0.0.1:8000/admin這時候我們發現我們還沒有管理員帳號?命令視窗通過python manage.py createsuperuser 建立管理員帳號7. 後臺 periodic task 中增加定時任務這裡配置定時任務可以做到最小單位 microsecond 微妙Interval 間隔Crontab 最小單位是Minute分鐘 分 時 日 月 星期8. 啟動心跳python manage.py celery beat9. 啟動 worker python manage.py celery worker -l info 10. 啟動 celery flower ,對任務進行監控pip install celery-flowerpython manage.py celery flower127.0.0.1:5555每次執行非同步task後, Celery都會返回AsyncResult物件作為結果. 你可以將其儲存, 然後在將來檢視該task是否執行成功和返回結果:
4. tasks.py程式碼DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] # celery djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/1' CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'redis://localhost:6379/2' CELERY_TASK_SERIALIZER = 'json' CELERY_ENABLE_UTC = True TIME_ZONE = 'Asia/Shanghai' CELERY_TIMEZONE = TIME_ZONE # email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "" EMAIL_HOST_PASSWORD = '' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER = "" EMAIL_PORT = 25 EMAIL_USE_TLS = True
#coding=utf-8 from __future__ import absolute_import, unicode_literals from celery import shared_task from django.core.mail import send_mail import logging logger = logging.getLogger(__name__) @shared_task def celery_send_email(subject, message, from_email, recipient_list, **kwrags): try: logger.info("\n開始傳送郵件") send_mail(subject, message, from_email, recipient_list, **kwrags) logger.info("郵件傳送成功") return 'success!' except Exception as e: logger.error("郵件傳送失敗: {}".format(e))
5.初始化資料庫python manage.py makemigrationspython manage.py migrate 6. 配置我們的celery-beatdjango提供了一個視覺化的後臺,啟動服務 python manage.py runserver 。瀏覽器訪問 :120.0.0.1:8000/admin這時候我們發現我們還沒有管理員帳號?命令視窗通過python manage.py createsuperuser 建立管理員帳號7. 後臺 periodic task 中增加定時任務這裡配置定時任務可以做到最小單位 microsecond 微妙Interval 間隔Crontab 最小單位是Minute分鐘