一 短信認證安全
https://cloud.tencent.com/document/product/382/11672app
1.下載模塊dom
pip install qcloudsms_py
2.麪條版測試
# 短信應用 SDK AppID appid = 1400279725 # SDK AppID 以1400開頭 # 短信應用 SDK AppKey appkey = "f1a377c327812cdd242ccb66a2fe895b" # 須要發送短信的手機號碼 phone_numbers = ["18539419683"] # 短信模板ID,須要在短信控制檯中申請 template_id = 457273 # NOTE: 這裏的模板 ID`7839`只是示例,真實的模板 ID 須要在短信控制檯中申請 # 簽名 sms_sign = "sages" # NOTE: 簽名參數使用的是`簽名內容`,而不是`簽名ID`。這裏的簽名"騰訊雲"只是示例,真實的簽名須要在短信控制檯中申請 # 隨機驗證碼 import random def get_code(): code = '' for i in range(4): code += str(random.randint(0,9)) return code from qcloudsms_py import SmsSingleSender from utils.logging import logger if __name__ == '__main__': ssender = SmsSingleSender(appid, appkey) # 驗證碼,和過時時間 短信模板中佔位符 code = get_code() print(code) params = [code,5] # 當模板沒有參數時,`params = []` try: result = ssender.send_with_param(86, phone_numbers[0], template_id, params, sign=sms_sign, extend="", ext="") if result and result['result'] == 0: print('發送成功') except Exception as e: print(e) logger.warning(e) print('發送短信失敗')
3.封裝版spa
# 短信應用 SDK AppID - SDK AppID 以1400開頭 APP_ID = ... # 短信應用 SDK AppKey APP_KEY = "..." # 短信模板ID,須要在短信控制檯中申請 TEMPLATE_ID = ... # 簽名 - 是`簽名內容`,而不是`簽名ID` SMS_SIGN= "..." # 電話前綴 MOBILE_PREFIX = 86
# 經過MacOS ssl安全認證 import ssl ssl._create_default_https_context = ssl._create_unverified_context # 獲取驗證碼的功能 import random def get_code(): code = '' for i in range(4): code += str(random.randint(0, 9)) return code # 短信發送者 from qcloudsms_py import SmsSingleSender from .settings import * sender = SmsSingleSender(APP_ID, APP_KEY) # 發送驗證碼 from utils.logging import logger
# 號碼 驗證碼 超時時間 def send_sms(mobile, code, exp): try: # 發送短信 號碼前綴 號碼 模板id 驗證碼 過時時間 簽名內容 response = sender.send_with_param(MOBILE_PREFIX, mobile, TEMPLATE_ID, (code, exp), sign=SMS_SIGN, extend="", ext="") # 成功 if response and response['result'] == 0: return True # 失敗 logger.warning('%s - %s' % ('短信發送失敗', response['result'])) except Exception as e: # 異常 logger.warning('%s - %s' % ('短信發送失敗', e)) return False
# 包對外提供的功能方法 from .sms import get_code, send_sms
from libs import txsms code = txsms.get_code() print(code) print(txsms.send_sms('電話', code, 5))