我正在尝试使用 Flask-Security,但在发送确认电子邮件时遇到了一些麻烦。我最终通过删除 flask_security/utils.py 中的一行来修复它。我删除了第 387 行,强制烧瓶邮件使用 app.config 的邮件发件人。
386: msg = Message(subject,
387: sender=_security.email_sender,
388: recipients=[recipient])
在删除之前,flask_mail.py 中的代码将失败,@ line 105(在 sanatize_address 方法内),因为传入的 addr 只是一个字符串,而不是一个元组。
102: def sanitize_address(addr, encoding='utf-8'):
103: if isinstance(addr, string_types):
104: addr = parseaddr(force_text(addr))
105: nm, addr = addr
我希望能够在每次安装时无需修改 flask_security/utils.py 即可运行我的代码。有什么建议么?这可能是我缺少的配置中的一个步骤,但我无法从烧瓶安全的文档中看出(它们有点受限)。
感谢您的帮助,以下是我的示例应用程序。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
import flask_security.utils
import flask_mail
# Create app
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
# Flask-Security Config
app.config['SECURITY_PASSWORD_SALT'] = 'super_secret'
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_CONFIRMABLE'] = True
app.config['SECURITY_RECOVERABLE'] = True
# Mail Config
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'example@gmail.com'
app.config['MAIL_PASSWORD'] = 'password'
app.config['MAIL_DEFAULT_SENDER'] = app.config['MAIL_USERNAME']
mail = flask_mail.Mail(app)
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
username = db.Column(db.String(255))
password = db.Column(db.String(255))
last_login_at = db.Column(db.DateTime())
current_login_at = db.Column(db.DateTime())
last_login_ip = db.Column(db.String(100))
current_login_ip = db.Column(db.String(100))
login_count = db.Column(db.Integer)
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary='roles_users',
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
db.create_all()
user_datastore.create_user(email='user@website.com', password=flask_security.utils.hash_password('password'))
db.session.commit()
# Views
@app.route('/')
@login_required
def home():
return('Here you go!')
if __name__ == '__main__':
app.run()