這是Flask-Security中文文檔翻譯第二波,再次聲明怜跑,此中文文檔全部由本人手擼翻譯。吠勘。性芬。
沒看過第一波的,點擊傳送門Flask-Security中文文檔之快速入門
后續(xù)文檔持續(xù)更新剧防。植锉。。
快速起步
- 基礎(chǔ)的SQLAlchemy應(yīng)用
- 基礎(chǔ)的SQLAlchemy會話應(yīng)用
- 基礎(chǔ)的MongoEngine應(yīng)用
- 基礎(chǔ)的Peewee應(yīng)用
- 郵箱配置
- 代理配置
基礎(chǔ)的SQLAlchemy應(yīng)用
SQLAlchemy安裝
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-sqlalchemy
SQLAlchemy應(yīng)用
以下代碼簡單地介紹了峭拘,如何通過SQLAlchemy快速使用Flask-Security:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, \
UserMixin, RoleMixin, login_required
# 創(chuàng)建應(yīng)用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
# 創(chuàng)建數(shù)據(jù)庫連接對象
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'))
# 設(shè)置 Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# 創(chuàng)建一個用戶來測試一下
@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()
基礎(chǔ)的SQLAlchemy會話應(yīng)用
SQLAlchemy安裝
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-sqlalchemy
SQLAlchemy應(yīng)用
以下代碼簡單地介紹了俊庇,如何通過SQLAlchemy快速使用Flask-Security:
我們將應(yīng)用分成了3個文件:app.py、database.py 鸡挠、models.py辉饱。你也可以創(chuàng)建一個文件夾來擴展你自己的代碼。
? 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
# 創(chuàng)建應(yīng)用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
# 設(shè)置 Flask-Security
user_datastore = SQLAlchemySessionUserDatastore(db_session,
User, Role)
security = Security(app, user_datastore)
# 創(chuàng)建一個用戶來測試一下
@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():
# 在此導(dǎo)入所有可能定義的模型宵凌,這樣他們將被正確注冊鞋囊。
# 否則,你將必須在調(diào)用init_db()之前導(dǎo)入他們瞎惫。
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'))
基礎(chǔ)的MongoEngine應(yīng)用
MongoEngine安裝
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-mongoengine
MongoEngine應(yīng)用
以下代碼簡單地介紹了溜腐,如何通過SQLAlchemy快速使用Flask-Security:
from flask import Flask, render_template
from flask_mongoengine import MongoEngine
from flask_security import Security, MongoEngineUserDatastore, \
UserMixin, RoleMixin, login_required
# 創(chuàng)建應(yīng)用(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
# 創(chuàng)建數(shù)據(jù)庫連接對象
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=[])
# 設(shè)置 Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# 創(chuàng)建一個用戶來測試一下
@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()
基礎(chǔ)的Peewee應(yīng)用
Peewee安裝
$ mkvirtualenv <your-app-name>
$ pip install flask-security flask-peewee
Peewee應(yīng)用
以下代碼簡單地介紹了,如何通過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
# 創(chuàng)建應(yīng)用(app)
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['DATABASE'] = {
'name': 'example.db',
'engine': 'peewee.SqliteDatabase',
}
# 創(chuàng)建數(shù)據(jù)庫連接對象
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沒有內(nèi)置的多對多關(guān)系瓜喇,我們需要這個中間類去連接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)
# 設(shè)置 Flask-Security
user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles)
security = Security(app, user_datastore)
# 創(chuàng)建一個用戶來測試一下
@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相結(jié)合去處理所有用戶與網(wǎng)站之間的郵箱通信挺益,所以為Flask-Mail配置您的郵箱服務(wù)信息是非常重要的。
下面的代碼展示了一個簡單的配置乘寒,您可以將下面的代碼直接加入您的Flask應(yīng)用代碼中:
# 在文件上面
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代理環(huán)境中添加一個額外的配置。下面的代碼展示了一個單個HTTP代理的配置烂翰。
# 在文件最上面
from werkzeug.config.fixers import ProxyFix
# 在'Create app'后
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
若想要了解更多關(guān)于ProxyFix的中間件夯缺,請閱讀Werkzeug文檔。