天天看點

Django 建構異步任務

  1. celery---适合多種不同架構
  • 消息隊列
    • 異步任務
    • 定時任務
  • 1.選擇并安裝消息容器(載體)-- redis作為載體--- 安裝指令pip install -U "celery[redis]"
  • 2.安裝Celery并建立第一個任務  --   pip install celery
    • Django 建構異步任務
  • 3.開啟工作程序,并調用任務
    • 進入tasks 目錄下運作 celery -A tasks worker --loglevel=info
    • celery woker --help
  • 4.記錄工作任務,并傳回結果
    •   add-->    add.delay()--異步調用
Django 建構異步任務

celery 在Django 中的應用

  • 1. 在setting 檔案同級建立 celery.py
  • 2.在setting 檔案同級,項目的init.py 中導入celery.app
    • Django 建構異步任務
  • 3.安裝  pip install django-celery-results
  • 4.   在setting 中配置相關屬性     
    • CELERY_BROKER_URL = 'redis://localhost:6379/1'
    • CELERY_ACCEPT_CONTENT = ['json']
    • #1.安裝 pip install django-celery-results,2.在install app 中注冊'django_celery_results',建立ORM ,存在mysql 資料庫中
    • #3.執行遷移 python manage.py migrate django_celery_results
    • #修改CELERY_RESULT_BACKEND參數為DB
    • #存在資料庫中:
    • CELERY_RESULT_BACKEND = 'django-db'
    • #存在緩存中
    • #CELERY_RESULT_BACKEND = ‘django-cache’
    • #原始,存在sqlite 資料庫中
    • #CELERY_RESULT_BACKEND = 'db+sqlite://results.sqlite'
    • CELERY_TASK_SERIALIZER = 'json'
    • 1.安裝 pip install django-celery-results,
    • 2.在install app 中注冊'django_celery_results',建立ORM ,存在mysql 資料庫中
  • 5.在app 中建立tasks.py
    • 建立tasks 任務
      • from time import sleep
      • from celery import shared_task
      • @shared_task
      • def add(a,b):
      • print("睡着了")
      • sleep(5)
      • return(a+b)
    • 建立路由,async異步調用 add ,add.delay(6.9),正常調用,add(6,9)
    • 啟動異步任務
      • celery -A RESTEnd worker -l info
      • 啟動伺服器
      • 通路 async 路由,傳回異步任務的 hash 值
      • 正常是能通路的,但本機環境redis 連接配接會有問題無法存儲在redis 中
      • https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

發郵件   https://docs.djangoproject.com/zh-hans/3.0/topics/email/#send-mail

  • from django.core.mail import send_mail
    • def send_mail(recieve):   subjects =  "Nisha"  massage = "hahah"  from_email="[email protected]"  recie、pient_list=(recieve,)
      • sendmail(subjects,message,from_mail,recipient_list)   (四個參數為必須的參數,recipient_list為元組)
      • 其他參數可寫在配置檔案中,465 為ssl 端口
Django 建構異步任務