您好,登錄后才能下訂單哦!
Flask和Django都是流行的Python Web框架,它們都提供了內(nèi)置的用戶認(rèn)證和授權(quán)系統(tǒng)。下面是如何在這兩個(gè)框架中集成用戶認(rèn)證與授權(quán)框架的簡(jiǎn)要說(shuō)明。
Flask是一個(gè)輕量級(jí)的Web框架,使用Flask-Login和Flask-Security等擴(kuò)展來(lái)實(shí)現(xiàn)用戶認(rèn)證和授權(quán)。
首先,安裝所需的擴(kuò)展:
pip install flask-login flask-sqlalchemy flask-bcrypt
導(dǎo)入并初始化Flask-Login:
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app)
定義用戶模型:
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import UserMixin
db = SQLAlchemy()
bcrypt = Bcrypt()
class User(UserMixin, db.Model):
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)
配置Flask-Login:
login_manager.login_view = 'auth.login'
創(chuàng)建登錄和注銷(xiāo)視圖:
from flask import render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required
from .models import User
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@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(username=form.username.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for('home'))
else:
flash('Invalid username or password')
return render_template('auth/login.html', title='Login', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
Flask-Security提供了更高級(jí)的用戶認(rèn)證和授權(quán)功能。以下是一個(gè)簡(jiǎn)單的示例:
安裝Flask-Security:
pip install flask-security
配置Flask-Security:
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
from flask import render_template
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), nullable=False)
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
@app.route('/')
@login_required
def home():
return render_template('home.html', title='Home')
Django是一個(gè)高級(jí)的Web框架,內(nèi)置了強(qiáng)大的用戶認(rèn)證和授權(quán)系統(tǒng)。
在settings.py
中啟用認(rèn)證系統(tǒng):
INSTALLED_APPS = [
...
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
創(chuàng)建用戶模型(可選):
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
# 添加自定義字段
pass
更新settings.py
以使用自定義用戶模型:
AUTH_USER_MODEL = 'yourapp.CustomUser'
創(chuàng)建登錄視圖:
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'auth/login.html', {'form': form})
創(chuàng)建注銷(xiāo)視圖:
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return redirect('home')
創(chuàng)建主頁(yè)視圖(需要登錄):
from django.contrib.auth.decorators import login_required
@login_required
def home_view(request):
return render(request, 'home.html', {'title': 'Home'})
在urls.py
中配置路由:
from django.urls import path
from .views import login_view, logout_view, home_view
urlpatterns = [
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('', home_view, name='home'),
]
Flask和Django都提供了強(qiáng)大的用戶認(rèn)證和授權(quán)系統(tǒng)。Flask使用擴(kuò)展如Flask-Login和Flask-Security來(lái)實(shí)現(xiàn)這些功能,而Django則內(nèi)置了這些功能。根據(jù)項(xiàng)目需求和個(gè)人喜好選擇合適的框架和擴(kuò)展。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。