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/
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 .
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")
from .celery_task import getcontent
def IndexView(request):
# use celery
getcontent.delay()
return render(request, 'test/index.html')
#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/