标签:https 很多 ret exception mod 成功 tin ice lse
使用云片网进行短信验证
1.注册云片网账号
2.开发者信息认证(审核通过)
3.新建签名(审核通过)
4.设置模板(审核通过)
5.查看api文档,发送短信形式有很多,国内国外,单条多条等,以国内单条为例。
6.官方文档中面向Python的代码写的比较麻烦,咱们可以自己写
###yunpian.py
import requests import json class YunPian(object): def __init__(self,api_key): self.api_key = api_key self.single_send_url = ‘https://sms.yunpian.com/v2/sms/single_send.json ‘ # 此地址可在api文档里查看 def send_sms(self,code,mobile): parmas = { ‘apikey‘:self.api_key, ‘mobile‘:mobile, ‘text‘:‘【暮雪生鲜】您的验证码是{code},非本人请可忽略‘%code } response = requests.post(self.single_send_url,data=parmas) re_dict = json.loads(response.text) print(re_dict) if __name__ == ‘__main__‘: # 测试用 yun_pian = YunPian(‘d6c4ddf50ab3131d46a1c662b94e‘) # 将apikey传入 yun_pian.send_sms(‘4651‘,‘13572551532‘) # 4651就是验证码,135...为要发送的手机号
### views.py
class SmsCodeViewset(CreateModelMixin,GenericViewSet): ‘‘‘ 短信验证码 ‘‘‘ serializer_class = SmsSerializer def generate_code(self): ‘‘‘ 生成四位数的验证码 ‘‘‘ seeds = ‘1234567890‘ random_str = [] for i in range(4): random_str.append(choice(seeds)) self.code = ‘‘.join(random_str) def create(self, request, *args, **kwargs): ‘‘‘ 发送验证码 ‘‘‘ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # 以下为重载内容 mobile = serializer.validated_data[‘mobile‘] self.generate_code() # 调用生成随机验证码 yun_pian = YunPian(APIKEY) # 实例化,将settings里配置的APIKEY传入 print(‘code:::‘,self.code,mobile) sms_status = yun_pian.send_sms(self.code,mobile) # 接收云片网发来的状态码,0表成功,其他代表错误 if sms_status[‘code‘] != 0: return Response({ ‘mobile‘:sms_status[‘msg‘] },status=status.HTTP_400_BAD_REQUEST) else: code_recod = models.VerifyCode(code=self.code, mobile=mobile) code_recod.save() return Response({ ‘mobile‘:mobile },status=status.HTTP_201_CREATED)
7.将本地ip添加到系统设置里的白名单里,否则系统不会让你发送信息的,,本地ip可直接进百度搜索‘本地ip’
标签:https 很多 ret exception mod 成功 tin ice lse
原文地址:https://www.cnblogs.com/gyk1030/p/11676795.html