1.1 注册账号
https://www.yuntongxun.com/user/login
1.2 登录即可看到开发者账号信息
1.3 添加测试账号
2.使用容联云发送代码测试
'''1. 安装容联云sdk''' pip install ronglian_sms_sdk # 免费测试文档地址:https://doc.yuntongxun.com/p/5a531a353b8496dd00dcdfe2'''2. 短信发送代码'''
# libs/rl_sms.py
from ronglian_sms_sdk import SmsSDKaccId = '8a216da874af5fff01750081830d19b0' #写自己的ID
accToken = '35dace6d4e424455a99613853eae3689'
appId = '8a216da874af5fff0175008183e519b7'def send_message(phone, datas):sdk = SmsSDK(accId, accToken, appId)tid = '1' # 测试模板id为: 1. 内容为: 【云通讯】您的验证码是{1},请于{2}分钟内正确输 入。# mobile = '13303479527'# datas = ('666777', '5')# 模板中的参数按照位置传递resp = sdk.sendMessage(tid, phone, datas)return resp
2.1在视图函数中使用
# verifications/views.pyclass SmsCodeView(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')#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) # bytesif redis_image_code:# bytes 转成 stringredis_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位验证码send_resp = send_message(phone, (code, "5"))#5.1保存code 到 redis# redis_client.setex(phone, 60 * 5, code) # phone:code, 5分钟有效期# 5.2 从redis中删除这个图片验证码, 以防再次被使用# redis_client.delete(image_code_uuid)# 5.3 使用 pipeline 批量操作pl = redis_client.pipeline()pl.setex(phone, 60 * 5, code)pl.delete(image_code_uuid)pl.execute()# 6.返回结果return Response({"code":0,"msg":"短信发送成功"})
在verifications/urls.py中添加路由
from django.urls import path
from . import views
urlpatterns = [path('sms_codes/',views.SmsCodeView.as_view())
]