其他分享
首页 > 其他分享> > Celery---手机短信异步发送

Celery---手机短信异步发送

作者:互联网

celery应用举例

celery的优点

celery特性

组件

Celery 扮演生产者和消费者的角色

celery架构图

在这里插入图片描述
在这里插入图片描述

产生任务的方式

celery的使用

推荐版本

python 3.6
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
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/2'
INSTALLED_APPS = [
 ...
 "djcelery",
 ...
]
python manage.py migrate
#如若不成功可以尝试⼀下命令语句
#python manage.py syncdb
import django

django.setup()

from aliyunsdkcore.client import AcsClient

from aliyunsdkcore.request import CommonRequest

from syl2.settings import ALY_ACCESSKEY_ID,ALY_ACCESSKEY_SECRET

import json,time

from celery import task

@task
def send_sms(phone,data):

    client = AcsClient(ALY_ACCESSKEY_ID, ALY_ACCESSKEY_SECRET, 'cn-hangzhou')

    #data ={ "code" : 123456 }

    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_185212884")

    request.add_query_param('TemplateParam', data)

    response1 = client.do_action(request)

    # python2: print(response)

    res = json.loads(str(response1, encoding='utf-8'))

    time.sleep(5)

    return 5 + 10
a、当settings.py中的djcelery.setup_loader()运⾏时, Celery便会查看所有INSTALLED_APPS中app⽬录中的tasks.py⽂件, 找到标记为task的function, 并将它们注册为celery task.
b、在执⾏djcelery.setup_loader()时, task是以INSTALLED_APPS中的app名,加.tasks.function_name注册的
c、⼀次需要注意 在impprt task时, 需要保持⼀致
d、如果我们由于python path不同⽽使⽤不同的引⽤⽅式时(例如在tasks.py中使⽤frommyproject.myapp.tasks import add形式), Celery将⽆法得知这是同⼀task, 因此可能会引起奇怪的bug
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from libs.captcha.captcha import captcha
from django.http.response import HttpResponse
import random
from verificationsapp.tasks import send_sms
from django_redis import get_redis_connection

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")
		print(phone)
		print(image_code_uuid)
		print(image_code)
		if not all([phone,image_code,image_code_uuid]):
		return Response({"code":4005,"msg":"参数不全"})
		#先获取redis ⾥的图⽚验证码来⽐对
		redis_cli = get_redis_connection("img_code")
		redis_img_code = redis_cli.get(image_code_uuid).decode()
		print(redis_img_code)
		print(image_code)
		if image_code.lower() != redis_img_code.lower():
		return Response({"code":4003,"msg":"参数错误"})
		#发送短信
		num = random.randint(100000,999999)
		print(num)
		send_data = {"code":10086}
		send_sms.delay(phone,send_data)
		# 删除redis⾥的image_code,保存phone_code
		#pipeline管道:作⽤就是把多个命令放在⼀起来执⾏
		pl = redis_cli.pipeline()
		pl.setex(phone,60*5,num)
		pl.delete(image_code_uuid)
		pl.execute()
		return Response({"code":0,"msg":"发送成功"})
python manage.py celery worker --loglevel=info
from celery import Celery, platforms
platforms.C_FORCE_ROOT = True

注册功能的完善

class UserView(APIView):
	def post(self,request):
		data = request.data
		# print(data)
		if not all([data.get('username'),data.get('password'),
		data.get('phone')]):
		return Response({"code":4003,'msg':"参数不完整"},status=200)
		# if data["password"] != data["password2"]:
		# return Response({"code": 4005, 'msg': "两次密码不⼀致"},
		status=200)
		redis_cli = get_redis_connection("img_code")
		redis_phone_num = redis_cli.get(data.get("phone")).decode()
		if redis_phone_num != data.get("code"):
		return Response({"code": 4005, 'msg': "短信验证码错误"}, status=200)
		try:
		user = serializers.CreateUserSer(data=data)
		user.is_valid()
		print(user.errors)
		user.save()
		res_data = {
		"code":0,
		"msg":"创建成功",
		"data":user.data
		}
		return Response(res_data)
		except Exception as e:
		# raise e
		res_data = {
		"code": 4009,
		"msg": "创建失败请重试",
		}
		return Response(res_data)

标签:---,code,celery,redis,request,Celery,手机短信,import,data
来源: https://blog.csdn.net/Quanliangxu/article/details/111626915