Django Celery4 异步任务配置和使用
Celery4 异步任务celery定时任务请看下面这篇博客Django Celery4 定时任务配置和使用#1 ...
扫描右侧二维码阅读全文
05
2021/11

Django Celery4 异步任务配置和使用

Celery4 异步任务

celery定时任务请看下面这篇博客
Django Celery4 定时任务配置和使用

#1 环境

Python3.7
celery==4.3.0
django==2.0.7
redis==3.2.1 # 低版本的redis不兼容celery

#2 项目配置

  • 新建Django项目
  • 配置和celery的定时任务一致

#3 需求分析
用户在"找回密码"功能中,点击发送邮件,会发送相应的数据到指定邮箱
发送邮箱需要比较长的时间处理
django 原生为单线程序,当第一个请求没有完成时,第二个请求辉阻塞,知道第一个请求完成,第二个请求才会执行。
不希望用户界面长时间存于等待邮箱发送中的状态

#4 开始

4.1 开一个发送邮箱接口

视图函数

from django.shortcuts import render,HttpResponse
from app.tasks import send_email
def email_api(request):
    send_email.delay() # 发送邮件(异步)
    return HttpResponse("邮件发送成功 !!! ")

tasks.py

@shared_task
def send_email():
    print("邮件发送中...")
    sleep(5) # 模拟发送邮件消耗的时间
    xxx.objects.create(
        name="发送邮件",
    ) # 把记录加到数据库中,(凭个人爱好,可加可不加)
    return "邮箱发送成功"

在app下__init__.py文件

from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

#4.2 测试*
访问接口
*4067736115.png

打开worker

celery multi start worker1 -A celery4

aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL0NveGh1YW5nL3lvc29yby9tYXN0ZXIvMjAxOTA1MDIxNzExNDctaW1hZ2UucG5n.png

注意事项

1 在app下的__init__.py必须加上那些代码,否则不会成功

Last modification:November 5th, 2021 at 03:27 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment