在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應用中實現用戶認證功能。