使用celery异步发送短信
1 在celery_task/mian.py
中添加发送短信函数
import os
import sys
import time
from celery import Celery
app = Celery('mycelery',
broker='redis://127.0.0.1:6379/14',
backend='redis://127.0.0.1:6379/15')
@app.task
def add(x, y):
return x + y
"""
'''1.启动celery'''
#1.1 单进程启动celery
celery -A main worker -l INFO
#1.2 celery管理
celery multi start celery_test -A celery_test -l debug --autoscale=50,5 # celery并发数:最多50个,最少5个
ps auxww|grep "celery worker"|grep -v grep|awk '{print $2}'|xargs kill -9 # 关闭所有celery进程
"""
CELERY_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
print(sys.path.insert(0, os.path.join(CELERY_BASE_DIR, '../syl')))
try:
@app.task(bind=True)
def send_sms_code(self, mobile, datas):
sys.path.insert(0, os.path.join(CELERY_BASE_DIR, '../syl'))
from libs.rl_sms import send_message
time.sleep(5)
try:
res = send_message(mobile, datas)
except Exception as e:
print(e)
res = '-1'
if res == '-1':
self.retry(countdown=5, max_retries=3, exc=Exception('短信发送失败'))
except Exception as e:
print(e)
2 在verifications/views.py
中添加celery发送短信试图函数
import os
import random
import re
import sys
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseForbidden
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
class SmsCodeView(APIView):
"""使用apiview的限流"""
permission_classes = (AllowAny,)
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, image_code)
if not all([phone, image_code, image_code_uuid]):
return Response({"code": 999, "msg": "参数不全"})
if not re.match(r'^1[3456789]\d{9}$', phone):
return Response({"code": 999, "msg": "手机号码不正确"})
redis_client = get_redis_connection('img_code')
phone_exists = redis_client.get(phone)
if phone_exists:
return Response({"code": 999, "msg": "频繁发送, 请稍后再试"})
redis_image_code = redis_client.get(image_code_uuid)
if redis_image_code:
redis_image_code = redis_image_code.decode()
if image_code.upper() != redis_image_code:
return Response({'code': 999, 'msg': '图片验证码不正确'})
code = '%06d' % random.randint(0, 999999)
from syl.settings import BASE_DIR
sys.path.insert(0, os.path.join(BASE_DIR, '../celery_task'))
from main import send_sms_code
send_sms_code.delay(phone, (code, "5"))
print(code)
pl = redis_client.pipeline()
pl.setex(phone, 60 * 5, code)
pl.delete(image_code_uuid)
pl.execute()
return Response({"code": 0, "msg": "短信发送成功"})
3 添加路由verifications/urls
from django.urls import path
from . import views
urlpatterns = [
path('sms_codes/', views.SmsCodeView.as_view()),
]
4.测试接口
http://192.168.56.100:8888/verify/sms_codes/
请求携带参数
{
"phone": 18538752511,
"image_code":"aed3", # 前端生成的 图形验证码
"image_code_uuid":"de8edce2-fc9f-11ea-9325-005056c00008" # 前端生成的uuid
}