这是Flask-Security中文文档翻译第二波,再次声明,此中文文档全部由本人手撸翻译。。。
没看过第一波的,点击传送门Flask-Security中文文档之快速入门
后续文档持续更新。。。
快速起步
- 基础的SQLAlchemy应用
- 基础的SQLAlchemy会话应用
- 基础的MongoEngine应用
- 基础的Peewee应用
- 邮箱配置
- 代理配置
基础的SQLAlchemy应用
SQLAlchemy安装
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-sqlalchemy
SQLAlchemy应用
以下代码简单地介绍了,如何通过SQLAlchemy快速使用Flask-Security:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
# 创建应用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
# 创建数据库连接对象
db = SQLAlchemy(app)
# 定义模型
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)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# 设置 Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# 创建一个用户来测试一下
@app.before_first_request
def create_user():
db.create_all()
user_datastore.create_user(email='matt@nobien.net', password='password')
db.session.commit()
# 视图
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
基础的SQLAlchemy会话应用
SQLAlchemy安装
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-sqlalchemy
SQLAlchemy应用
以下代码简单地介绍了,如何通过SQLAlchemy快速使用Flask-Security:
我们将应用分成了3个文件:app.py、database.py 、models.py。你也可以创建一个文件夹来扩展你自己的代码。
• app.py
from flask import Flask
from flask_security import Security, login_required, \
SQLAlchemySessionUserDatastore
from database import db_session, init_db
from models import User, Role
# 创建应用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
# 设置 Flask-Security
user_datastore = SQLAlchemySessionUserDatastore(db_session,
User, Role)
security = Security(app, user_datastore)
# 创建一个用户来测试一下
@app.before_first_request
def create_user():
init_db()
user_datastore.create_user(email='matt@nobien.net', password='password')
db_session.commit()
# 视图
@app.route('/')
@login_required
def home():
return render('Here you go!')
if __name__ == '__main__':
app.run()
• database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:////tmp/test.db', \
convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# 在此导入所有可能定义的模型,这样他们将被正确注册。
# 否则,你将必须在调用init_db()之前导入他们。
import models
Base.metadata.create_all(bind=engine)
• models.py
from database import Base
from flask_security import UserMixin, RoleMixin
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Boolean, DateTime, Column, Integer, \
String, ForeignKey
class RolesUsers(Base):
__tablename__ = 'roles_users'
id = Column(Integer(), primary_key=True)
user_id = Column('user_id', Integer(), ForeignKey('user.id'))
role_id = Column('role_id', Integer(), ForeignKey('role.id'))
class Role(Base, RoleMixin):
__tablename__ = 'role'
id = Column(Integer(), primary_key=True)
name = Column(String(80), unique=True)
description = Column(String(255))
class User(Base, UserMixin):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
email = Column(String(255), unique=True)
username = Column(String(255))
password = Column(String(255))
last_login_at = Column(DateTime())
current_login_at = Column(DateTime())
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer)
active = Column(Boolean())
confirmed_at = Column(DateTime())
roles = relationship('Role', secondary='roles_users',
backref=backref('users', lazy='dynamic'))
基础的MongoEngine应用
MongoEngine安装
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-mongoengine
MongoEngine应用
以下代码简单地介绍了,如何通过SQLAlchemy快速使用Flask-Security:
from flask import Flask, render_template
from flask_mongoengine import MongoEngine
from flask_security import Security, MongoEngineUserDatastore, \
UserMixin, RoleMixin, login_required
# 创建应用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
# MongoDB 配置
app.config['MONGODB_DB'] = 'mydatabase'
app.config['MONGODB_HOST'] = 'localhost'
app.config['MONGODB_PORT'] = 27017
# 创建数据库连接对象
db = MongoEngine(app)
class Role(db.Document, RoleMixin):
name = db.StringField(max_length=80, unique=True)
description = db.StringField(max_length=255)
class User(db.Document, UserMixin):
email = db.StringField(max_length=255)
password = db.StringField(max_length=255)
active = db.BooleanField(default=True)
confirmed_at = db.DateTimeField()
roles = db.ListField(db.ReferenceField(Role), default=[])
# 设置 Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# 创建一个用户来测试一下
@app.before_first_request
def create_user():
user_datastore.create_user(email='matt@nobien.net', password='password')
# 视图
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
基础的Peewee应用
Peewee安装
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-peewee
Peewee应用
以下代码简单地介绍了,如何通过SQLAlchemy快速使用Flask-Security:
from flask import Flask, render_template
from flask_peewee.db import Database
from peewee import *
from flask_security import Security, PeeweeUserDatastore, \
UserMixin, RoleMixin, login_required
# 创建应用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['DATABASE'] = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',
}
# 创建数据库连接对象
db = Database(app)
class Role(db.Model, RoleMixin):
name = CharField(unique=True)
description = TextField(null=True)
class User(db.Model, UserMixin):
email = TextField()
password = TextField()
active = BooleanField(default=True)
confirmed_at = DateTimeField(null=True)
class UserRoles(db.Model):
# 因为peewee没有内置的多对多关系,我们需要这个中间类去连接user和role
user = ForeignKeyField(User, related_name='roles')
role = ForeignKeyField(Role, related_name='users')
name = property(lambda self: self.role.name)
description = property(lambda self: self.role.description)
# 设置 Flask-Security
user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles)
security = Security(app, user_datastore)
# 创建一个用户来测试一下
@app.before_first_request
def create_user():
for Model in (Role, User, UserRoles):
Model.drop_table(fail_silently=True)
Model.create_table(fail_silently=True)
user_datastore.create_user(email='matt@nobien.net', password='password')
# 视图
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
邮箱配置
Flask-Security与Flask-Mail相结合去处理所有用户与网站之间的邮箱通信,所以为Flask-Mail配置您的邮箱服务信息是非常重要的。
下面的代码展示了一个简单的配置,您可以将下面的代码直接加入您的Flask应用代码中:
# 在文件上面
from flask_mail import Mail
# 在'Create app'后
app.config['MAIL_SERVER'] = 'smtp.example.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'username'
app.config['MAIL_PASSWORD'] = 'password'
mail = Mail(app)
若想要了解更多Flask-Mail的配置信息,请阅读Flask-Mail文档。
代理配置
用户追踪特性需要在HTTP代理环境中添加一个额外的配置。下面的代码展示了一个单个HTTP代理的配置。
# 在文件最上面
from werkzeug.config.fixers import ProxyFix
# 在'Create app'后
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
若想要了解更多关于ProxyFix的中间件,请阅读Werkzeug文档。