先下载
pip install aliyun-python-sdk-core
这里的短信验证是阿里云的短信验证。
先在阿里云创建一个签名管理和模块管理。
登录上阿里云,右上角是头像,头像左边控制台,点开控制台,然后搜索短信服务,左边栏上点开国内信息,就可以看到签名模块和管理模块
设置AK和SK
将你的鼠标放在你的头像上,下面会出来一个AccessKey 管理,点进去激活就好,然后把AK和SK记下就好。
在项目里面创建一个utils在下面在创建一个BaseView.py
一定要看好目录等级
BaseView.py:
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from rest_framework_jwt.settings import api_settings
import json
def create_token(user):
# 生成jwt_token,user是一个对象或者是查询结果"key":"value"
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
def send_sms(phone, data):
client = AcsClient('LTAI4G1MvKrBJjincAogP3qE', 'D1TjXd1DyovJLr6vFwC2lxeEAFaKl2', 'cn-hangzhou')
# client = AcsClient('AK', 'SK', 'cn-hangzhou')
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', "ABC商城")
request.add_query_param('TemplateCode', "SMS_205403766")
request.add_query_param('TemplateParam', data)
response = client.do_action(request)
# python2: print(response)
res = json.loads(str(response, encoding='utf-8'))
print(res)
if res['Code'] == "OK":
return True
else:
return False
views:
from rest_framework.views import APIView
from rest_framework.response import Response
import random
from utils.BaseView import send_sms
class SMSCodeView(APIView):
def post(self, request):
phone = request.data.get('phone')
num = random.randint(100000, 999999)
send_data = {'code': num}
res = send_sms(phone, send_data)
if res:
return Response({'code': 0, 'msg': '成功'})
else:
return Response({'code': 9999, 'msg': '哦不'})
然后自己在配置一下路由就可以了
代码可以直接复制,改修改的东西,你改成你的就可以。