1) 获取accesskey

2) 创建子key

3) 拿到子key

  1. # 同一个手机号
  2. 1分钟内短信发送条数不超过:1
  3. 1小时内短信发送条数不超过:5
  4. 1个自然日内短信发送条数不超过:10

  1. pip install aliyun-python-sdk-core

  1. # 测试的时候要把你的accesskeyid,accessSecret,签名内容,模板code,短信内容(json格式)填入

1)libs/ali_sms/ali_sms_hander.py

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. from aliyunsdkcore.client import AcsClient
  4. from aliyunsdkcore.request import CommonRequest
  5. import json,random
  6. from utils.logging import logger
  7. from django.conf import settings
  8. #-------阿里sms--------
  9. # ACCESS_KEY_SECRET_SMS = ACCESS_KEY_SECRET_SMS
  10. # ACCESS_KEY_ID_SMS = ACCESS_KEY_ID_SMS
  11. # REGIONID = "cn-beijing"
  12. # SIGN_NAME = "路飞学城"
  13. # TEMPLATE_CODE = "SMS_153790638"
  14. #------end--------------
  15. def send_sms(mobile,code):
  16. client = AcsClient(settings.ACCESS_KEY_ID_SMS, settings.ACCESS_KEY_SECRET_SMS, settings.REGIONID)
  17. request = CommonRequest()
  18. request.set_accept_format(\'json\')
  19. request.set_domain(\'dysmsapi.aliyuncs.com\')
  20. request.set_method(\'POST\')
  21. request.set_protocol_type(\'https\') # https | http
  22. request.set_version(\'2017-05-25\')
  23. request.set_action_name(\'SendSms\')
  24. request.add_query_param(\'RegionId\', settings.REGIONID)
  25. request.add_query_param(\'PhoneNumbers\',str(mobile))
  26. request.add_query_param(\'SignName\', settings.SIGN_NAME)
  27. request.add_query_param(\'TemplateCode\', settings.TEMPLATE_CODE)
  28. TemplateParam = json.dumps({"code":code})
  29. request.add_query_param(\'TemplateParam\', TemplateParam)
  30. try:
  31. response = client.do_action_with_exception(request)
  32. response = json.loads(response)
  33. print(response)
  34. except Exception as e:
  35. logger.error(f\'短信发送失败:{mobile},{e}\')
  36. return False
  37. if response and response.get(\'Code\') == \'OK\':
  38. return True
  39. logger.error(f"短信发送失败:{mobile},{response.get(\'Message\')}")
  40. return False
  41. def get_code():
  42. code = \'\'
  43. for i in range(4):
  44. code += str(random.randint(0, 9))
  45. return code

2)api调用

  1. class SMSAPIView(APIView):
  2. def post(self,request,*args,**kwargs):
  3. mobile = request.data.get(\'mobile\')
  4. if not mobile or not re.match(r\'^1[3-9][0-9]{9}$\', mobile):
  5. return APIResponse(1, \'手机号有误\')
  6. # 产生验证码
  7. code = get_code()
  8. # 通知第三方发送短信
  9. result = send_sms(mobile,code)
  10. # 失败:
  11. if not result:
  12. return APIResponse(1,\'短信发送失败\')
  13. # 成功:
  14. # todo: 成功后存到redis里面
  15. return APIResponse(0,\'短信发送成功\')

版权声明:本文为zhangmingyan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangmingyan/articles/12021045.html?ivk_sa=1024320u