Django 構建非同步任務
阿新 • • 發佈:2021-10-13
- celery---適合多種不同框架
- 訊息佇列
- 非同步任務
- 定時任務
- 1.選擇並安裝訊息容器(載體)-- redis作為載體--- 安裝命令pip install -U "celery[redis]"
- 2.安裝Celery並建立第一個任務 -- pip install celery
- 3.開啟工作程序,並呼叫任務
- 進入tasks 目錄下執行 celery -A tasks worker --loglevel=info
- celery woker --help
- 4.記錄工作任務,並返回結果
- add--> add.delay()--非同步呼叫
- 1. 在setting 檔案同級建立 celery.py
- 2.在setting 檔案同級,專案的init.py 中匯入celery.app
- 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 資料庫中
- #3.執行遷移 python manage.py migrate django_celery_results
- 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
- 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 埠