文章目录
1. 注册容联云账号1.1 注册账号1.2 登录即可看到开发者账号信息1.3 添加测试账号
2. 使用容联云发送代码测试3. 在视图函数中使用3.1 在verifications/urls.py中添加路由3.2 写视图函数
1. 注册容联云账号
1.1 注册账号
https://www.yuntongxun.com/user/login
1.2 登录即可看到开发者账号信息
1.3 添加测试账号
2. 使用容联云发送代码测试
'''1. 安装容联云sdk'''
pip install ronglian_sms_sdk
'''2. 短信发送代码'''
accId
= '8a216da8747ac98201749c0de38723b7'
accToken
= '86072b540b4648229b27400414150ef2'
appId
= '8a216da8747ac98201749c0de45123be'
def send_message(phone
, datas
):
sdk
= SmsSDK
(accId
, accToken
, appId
)
tid
= '1'
入。
resp
= sdk
.sendMessage
(tid
, phone
, datas
)
return resp
3. 在视图函数中使用
3.1 在verifications/urls.py中添加路由
urlpatterns
= [
path
('sms_codes/', views
.SmsCodeView
.as_view
())
]
3.2 写视图函数
from rest_framework
.permissions
import AllowAny
from rest_framework
.views
import APIView
from rest_framework
.response
import Response
import re
import random
from utils
.rl_sms
import send_message
class SmsCodeView(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')
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)
send_resp
= send_message
(phone
, (code
, "5"))
pl
= redis_client
.pipeline
()
pl
.setex
(phone
, 60 * 5, code
)
pl
.delete
(image_code_uuid
)
pl
.execute
()
return Response
({"code": 0, "msg": "短信发送成功"})