celery--异步任务
用于:
超时任务且与前面没有直接关系
celery 五大部件:
beat(调度器)
broducers(生产者)
broker(载体)
worker(执行者)
backend(结束时的载体)
celery使用
django-celery比celery的配置更简单
注意:如果版本过高会报错
建议版本
Django == 2.2.6
django-celery == 3.3.1
django-redis == 4.11.0
redis == 2.10.6
celery == 3.1.26.post2
使用前配置
settings.py
# celery 配置 import djcelery djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/2' INSTALLED_APPS = [ 'djcelery', ]
创建celery所需要的数据表
python manage.py migrate #如若不成功可以尝试一下命令语句 #python manage.py syncdb
在app里建立tasks.py文件来写入需要执行的异步任务
from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest # from dsyl.settings import import json,time from celery import task @task def send_sms(phone,data): client = AcsClient('LTAI4G9xk5Pqa1T2jowLhG6P', 'p0coikLbSekk2epMCLAGtc2e6243YB', 'cn-hangzhou') request = CommonRequest() request.set_accept_format('json') request.set_domain('dysmsapi.aliyuncs.com') request.set_method('POST') request.set_protocol_type('https') # https | http request.set_version('2017-05-25') request.set_action_name('SendSms') request.add_query_param('RegionId', "cn-hangzhou") request.add_query_param('PhoneNumbers', phone) request.add_query_param('SignName', "美多商城") request.add_query_param('TemplateCode', "SMS_205890696") request.add_query_param('TemplateParam', data) response = client.do_action(request) # python2: print(response) print(str(response, encoding='utf-8')) time.sleep(5) return 5+10
view.py
class SendSmsCode(APIView): def post(self, request): # 获取数据 phone = request.data.get('phone') image_code = request.data.get('image_code') image_code_uuid = request.data.get('image_code_uuid') # 数据验证 if not all([phone, image_code, image_code_uuid]): return Response({'code': 401, 'msg': '参数不完整'}) # 逻辑入库 # 1.图片验证 # 1.1连接redis redis_client = get_redis_connection('img_code') # 1.2获取redis里的img_code redis_img_code = redis_client.get(image_code_uuid).decode() print(redis_img_code) # 1.3比较两个img_code if redis_img_code.lower() != image_code.lower(): return Response({'code': 405, 'msg': '图片验证码错误'}) # 2.发送短信 # 2.1获取手机号 # 2.2生成短信验证码 number = random.randint(100000, 999999) data = {'code': number} print(data) # 2.3发送短信 send_sms.delay(phone, data) # 3.将验证码信息存入redis # 3.1连接redis,1.1已连接 redis_client.setex(phone, 60 * 60, number) # 3.3删除img_code redis_client.delete(image_code_uuid) # 返回 return Response({"code": 0, 'msg': '发送成功'})
启动celery
首先正常启动你的django任务,然后启动celery服务即可
python manage.py celery worker --loglevel=info
如果报错不让超级管理员来启动,在settings.py加入以下配置
from celery import Celery, platforms platforms.C_FORCE_ROOT = True
注意
celery与3.7版本兼容问题
在 celery 官方的提议下,建议将 async 文件的文件名改成 asynchronous
Python37\Lib\site-packages\kombu\async
需要修改的文件
Python37\Lib\site-packages\celery\utils\timer2.py
Python37\lib\site-packages\celery\concurrency\asynpool.py
Python37\lib\site-packages\celery\worker\components.py
Python37\lib\site-packages\celery\worker\autoscale.py
Python37\lib\site-packages\celery\worker\consumer.py