在Flask中实现用户认证可以通过以下步骤:
pip install Flask-Login
from flask_login import UserMixin
class User(UserMixin):
def __init__(self, id):
self.id = id
from flask import Flask, request, redirect, url_for
from flask_login import LoginManager, login_user
app = Flask(__name__)
login_manager = LoginManager(app)
@login_manager.user_loader
def load_user(user_id):
return User(user_id)
@app.route('/login', methods=['POST'])
def login():
user_id = request.form['user_id']
user = User(user_id)
login_user(user)
return redirect(url_for('index'))
from flask import redirect, url_for
from flask_login import login_required
@app.route('/protected')
@login_required
def protected():
return 'You are logged in!'
from flask import redirect, url_for
from flask_login import logout_user
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
通过以上步骤,你可以在Flask应用中实现用户认证功能。