03.celery异步发送短信验证码
1.使用celery异步发送短信验证码#
1.1 在celery_task/mian.py
中添加发送短信函数#
# celery项目中的所有导包地址, 都是以CELERY_BASE_DIR为基准设定.
# 执行celery命令时, 也需要进入CELERY_BASE_DIR目录执行.
CELERY_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
@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 接收发送结果, 成功是:0, 失败是:-1
res = send_message(mobile, datas)
except Exception as e:
res = '-1'
if res == '-1':
# 如果发送结果是 -1 就重试.
self.retry(countdown=5, max_retries=3, exc=Exception('短信发送失败'))
1.2 在verifications/views.py
中添加celery发送短信试图函数#
class SmsCodeView(APIView):
"""使用apiview的限流"""
# 1. 所有人可以访问
permission_classes = (AllowAny,)
def post(self, request):
# 1. 获取参数
phone = request.data.get('phone') # 手机号
image_code = request.data.get('image_code') # 图片验证码
image_code_uuid = request.data.get('image_code_uuid') # 前端生成的uuid
# 2. 检查参数
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": "手机号码不正确"})
# 3. 检查是否发送
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) # bytes
if redis_image_code:
# bytes 转成 string
redis_image_code = redis_image_code.decode()
# 比较用户提供的图片内容是否和redis中保存的一致
if image_code.upper() != redis_image_code:
return Response({'code': 999, 'msg': '图片验证码不正确'})
# 4. 发送
code = '%06d' % random.randint(0, 999999) # 随机6位验证码
from syl.settings import BASE_DIR
sys.path.insert(0, os.path.join(BASE_DIR, '../celery_task'))
from main import send_sms_code # 必须这么写, 从main中导包
send_sms_code.delay(phone, (code, "5"))
print(code)
# 5.使用 pipeline 批量操作
pl = redis_client.pipeline() # 实例化pipeline对象
pl.setex(phone, 60 * 5, code) # 存储phone:code, 5分钟有效期
pl.delete(image_code_uuid) # 从redis中删除这个图片验证码, 以防再次被使用
pl.execute()
# 6. 返回结果
return Response({"code": 0, "msg": "短信发送成功"})
1.3 添加路由#
urlpatterns = [
path('sms_codes/', views.SmsCodeView.as_view()),
]
2.测试接口#
- 接口URL
http://192.168.56.100:8888/user/sms_codes/
- 请求携带参数
{
"phone": 18538752511,
"image_code":"aed3", # 前端生成的 图形验证码
"image_code_uuid":"de8edce2-fc9f-11ea-9325-005056c00008" # 前端生成的uuid
}
作者:就学45分钟
出处:https://www.cnblogs.com/tjw-bk/p/13778699.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
分类:
Django-项目开发
, 工具--celery
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了