1. 程式人生 > 實用技巧 >最長公共子串

最長公共子串

  1. 註冊容聯雲賬號

  1. 使用容聯雲傳送簡訊

# 安裝容聯雲
pip install ronglian_sms_sdk

''' 簡訊傳送程式碼 '''
#libs/rl_sms.py
from ronglian_sms_sdk import SmsSDK

accId = '上圖ACCOUNT SID'
accToken = '上圖AUTH TOKEN'
appId = '上圖APPID'


def send_message(phone,datas):
sdk = SmsSDK(accId,accToken, appId)
tid = '1' # 測試模板id為: 1. 內容為: 【雲通訊】您的驗證碼是{1},請於{2}分鐘內正確輸 入。
# mobile = '13303479527'
# datas = ('666777', '5')
# 模板中的引數按照位置傳遞
resp = sdk.sendMessage(tid, phone, datas)
return resp
  1. 在檢視函式中使用

# verifications/urls.py 中新增路由
urlpatterns = [
path('sms_codes/', views.SmsCodeView.as_view()),
]

# 寫檢視函式
# verifications/views.py
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):
# 1.所有人可以訪問
permission_class = (AllowAny, )
def post(self, request):
# 1.獲取引數
phone = request.data.get('phone')
image_code = request.data.get('image_code')
image_code_uuid = request.data.get('image_code_uuid')

# 2.檢查引數
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":"手機號碼不正確"})

# 3.檢查是否傳送
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) #bytes
if rediss_image_code:
# bytes 轉成 string
redis_image_code = redis_image_code.decode()

# 比較使用者提供的圖片內容是否和redis中儲存的一致
if image_code.upper() != redis_image_code:
return Response({'code':999, 'msg':'圖片驗證碼不正確'})

# 4. 傳送
code = '%06d' % random.randint(0,999999) # 隨機6位驗證碼
send_resp = send_message(phone, (code, "5"))

# 5.1 儲存code到redis中
# redis_client.delete(image_code_uuid)

# 5.2 從redis中刪除這個圖片驗證碼,以防再次使用
# redis_client.delete(image_code_uuid)

# 5.3使用pipeline 批量操作
pl = redis_client.pipeling()
pl.setex(phone, 60*5, code)
pl.delete(image_code_uuid)
pl.execute()

# 6. 返回結果
return Response({"code":0, "msg":"簡訊傳送成功"})