Flask專案中實現簡訊驗證碼和郵箱驗證碼功能
阿新 • • 發佈:2020-01-09
Flask是一個用Python編寫的Web應用程式框架,Flask是python的web框架,最大的特徵是輕便,讓開發者自由靈活的相容要開發的feature。它由Armin Ronacher開發,他領導一個名為Pocco的國際Python愛好者團隊。Flask基於Werkzeug WSGI工具包和Jinja2模板引擎。兩者都是Pocco專案。
這篇文章給大家介紹Flask專案中實現簡訊驗證碼和郵箱驗證碼功能,具體內容如下所示:
一、傳送郵箱驗證碼
1、使用QQ郵箱傳送驗證碼
①配置
開啟pop3/smtp服務
2、應用
①前端頁面
②config.py
# 郵箱配置 # MAIL_USE_TLS:埠號587 # MAIL_USE_SSL:埠號465 # QQ郵箱不支援非加密方式傳送郵件 # 傳送者郵箱的伺服器地址 MAIL_SERVER = "smtp.qq.com" MAIL_PORT = '587' MAIL_USE_TLS = True # MAIL_USE_SSL MAIL_USERNAME = "[email protected]" MAIL_PASSWORD = "*****" # 生成授權碼,授權碼是開啟smtp服務後給出的 MAIL_DEFAULT_SENDER = [email protected]
③views.py
點選獲取驗證碼,進入到以下檢視,傳送郵件,把驗證碼存到memcache資料庫。
from flask_mail import Message,Mail mail = Mail() @bp.route('/email_captcha/') @login_requires def email_captcha(): email = request.args.get('email') if not email: return restful.params_error('請輸入郵箱') #restful. 封裝的函式,返回前端資料 ''' 生成隨機驗證碼,儲存到memcache中,然後傳送驗證碼,與使用者提交的驗證碼對比 ''' captcha = str(uuid.uuid1())[:6] # 隨機生成6位驗證碼 # 給使用者提交的郵箱傳送郵件 message = Message('Python論壇郵箱驗證碼',recipients=[email],body='您的驗證碼是:%s' % captcha) try: mail.send(message) # 傳送 except: return restful.server_error() mbcache.set(email,captcha) return restful.success()
點選立即修改,
以post請求發到後臺,對使用者提交的資料進行校驗:拿出memcache中儲存的驗證碼與使用者提交的驗證碼對比,校驗郵箱格式。校驗通過後把新郵箱儲存到資料庫,返回前端提示資訊。郵箱驗證功能完成。
二、實現簡訊驗證碼
1、平臺以及配置
平臺:阿里大於
配置:1、新增模板
2、添加簽名
3、獲取
即下面的key和secret
2、flask中使用
config.py
#傳送簡訊驗證碼配置 KEY="*******" SECRET="*******" alidayu.py傳送簡訊功能實現 from aliyunsdkcore.client import AcsClient #需要先下載包 from aliyunsdkcore.request import CommonRequest import config def send_sms(telephone,captcha): client = AcsClient(config.KEY,config.SECRET,'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',telephone) #傳送的手機號 request.add_query_param('SignName',"flask論壇") #SignName簽名 request.add_query_param('TemplateCode',"SMS_174806057") #模板id code = {} code['code'] = captcha request.add_query_param('TemplateParam',code) #模板中要填入的資料 response = client.do_action(request) # python2: print(response) return str(response,encoding='utf-8')
呼叫是send_sms('手機號','驗證碼'),即可傳送簡訊。(當然餘額得有錢.)
總結
以上所述是小編給大家介紹的Flask專案中實現簡訊驗證碼和郵箱驗證碼功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!