Flask邮箱认证以及头像
《Flask Web开发》书中关于邮箱认证功能此处使用qq邮箱完成。
首先到qq邮箱中开启SMTP服务,百度有很多教程。
发送邮件功能:
from threading import Thread
from flask import current_app, render_template
from flask.ext.mail import Message
from Main import mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(to, subject, template, **kwargs):
app = current_app._get_current_object()
msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + ' ' + subject,
sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[app, msg])
thr.start()
return thr
邮箱的配置:
app.config['MAIL_DEBUG'] = True
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['MAIL_SERVER'] = 'smtp.qq.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USERNAME'] = 'xxxxxx@qq.com'
app.config['MAIL_PASSWORD'] = 'zzzzzzz'
app.config['MAIL_DEFAULT_SENDER'] = 'xxxxxxxxxxxx@qq.com'
app.config['FLASKY_MAIL_SUBJECT_PREFIX']='[blog]'
app.config['FLASKY_MAIL_SENDER']='xxxxxxxxxxx@qq.com'
头像功能通过avatar实现
def gravatar(self, size=100, default='identicon', rating='g'):
if request.is_secure:
url = 'https://secure.gravatar.com/avatar'
else:
url = 'http://www.gravatar.com/avatar'
hash = self.avatar_hash or hashlib.md5(
self.email.encode('utf-8')).hexdigest()
return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
url=url, hash=hash, size=size, default=default, rating=rating)
根据用户邮箱生成对应的hash码发送到avatar网站即可生成头像
源码在: