在 Flask 中实现用户认证和授权通常涉及到以下几个方面:用户模型、登录、注册、用户认证、用户授权等。下面是一个简单的步骤和示例,以实现基本的用户认证和授权。
1. 安装 Flask 和 Flask 扩展:
pip install Flask Flask-SQLAlchemy Flask-Login Flask-WTF
2. 创建 Flask 应用:
# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # 使用 SQLite 数据库,你可以选择其他数据库
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login' # 指定登录页面的端点
from your_app import routes, models
3. 创建用户模型:
# models.py
from datetime import datetime
from flask_login import UserMixin
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(60), nullable=False)
4. 创建表单(使用 Flask-WTF):
# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember = SubmitField('Remember Me')
submit = SubmitField('Login')
5. 创建路由和视图:
# routes.py
from flask import render_template, url_for, flash, redirect
from your_app import app, db, bcrypt
from your_app.forms import RegistrationForm, LoginForm
from your_app.models import User
from flask_login import login_user, current_user, logout_user, login_required
@app.route("/")
def home():
return render_template('home.html')
@app.route("/register", methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(username=form.username.data, email=form.email.data, password=hashed_password)
db.session.add(user)
db.session.commit()
flash('Your account has been created!', 'success')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('home'))
else:
flash('Login unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for('home'))
@app.route("/account")
@login_required
def account():
return render_template('account.html', title='Account')
6. 创建模板:
创建相应的HTML模板,例如 templates/register.html
, templates/login.html
, templates/account.html
等,以及基础的 templates/base.html
模板。
7. 运行应用:
python app.py
以上是一个简单的用户认证和授权的示例。这包括用户注册、登录、登出、账户页面等功能。你可以根据项目的需要扩展这些功能,例如添加更多的用户信息、用户角色和权限等。