程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to use celery in Django?

編輯:Python

Recently I wrote a Django project , It happens that there is a function of data acquisition that has a particularly large delay (30s about ), Seriously affect users' browsing experience , I thought of trying to use celery solve . How to put it? ? It's not difficult to meet. , The hard ones will not. . At first, it felt quite simple , For two days error, I found a video system to study ,emmm Still have error. I mainly want to pass Model To store data , Various class Quote error , If it can't be solved, they all want to operate directly MySQL To write the library .

https://www.emperinter.info/2022/06/15/how-to-use-celery-in-django/

Use

Let me first talk about how to use a file , Of course, you can also build a class task Separate from the configuration file and try to decouple , Subsequent maintenance is more convenient . The message oriented middleware is Redis, Of course, you can also choose mq wait .

  • stay models.py Same as directory creation celery_task.py, I mainly use asynchronous , Regular tasks are also similar . The contents are as follows , The main thing is django And models References to .
from celery import Celery
import time
import os
import django
# Be careful Project Change to your own project name 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings')
django.setup()
from test.models import article
backend='redis://127.0.0.1:6379/1' # The database stores asynchronous results 
broker='redis://127.0.0.1:6379/2' # Message middleware (0-16 individual , Choose one of them ) 
cel=Celery('test',backend=backend,broker=broker) # ’test‘ celery A name for 
@cel.task()
def getcontent():
article.objects.create(description ="description", content = "content")
  • views.py
from .celery_task import getcontent
def IndexView(request):
# use celery 
getcontent.delay()
return render(request, 'test/index.html')
  • Start under the project path , Here we mainly pay attention to celery5.x How to start and gevent And module install .
#celery5.x start-up 
#celery --app test.celery_task worker -l info -P gevent
celery worker -A test.celery_task -l info -P gevent

https://www.emperinter.info/2022/06/15/how-to-use-celery-in-django/


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved