Flask框架Flask-Principal基本用法实例分析

时间:2022-12-02 22:24:44

本文实例讲述了Flask框架Flask-Principal基本用法。分享给大家供大家参考,具体如下:

Flask-Principal是Flask框架的一个扩展,主要主件是Identity,Needs,Permission和IdentityContext。

  • Identity:代表用户,从各个位置存储和加载每个请求,包含用户拥有的访问权限。
  • Needs:需求是访问控制的最小粒度,代表了这种情况的具体参数。例如:管理用户、可以编辑帖子.
  • Permission:权限
  • IdentityContext:针对某个权限特定的上下文,可用作上下文管理器或装饰器

安装

?
1
pip install flask-principal

初始化

?
1
2
3
from flask_principal import Principal
principal = Principal()
principal.init_app(app)

权限管理

permissions.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from flask-principal import Permission,RoleNeed
from functools import wraps
# 定义相关角色
NORMAL = "NORMAL"
ADMIN = "ADMIN"
ROLES = (
  ("NORMAL","普通用户"),
  ("ADMIN","管理员")
)
admin_permission = Permission(RoleNeed(ADMIN))
def admin_authority(func):
  @wraps
  def decorated_view(*args,**kwargs):
    if admin_permission.can():
      return func(*args,**kwargs)
    else:
      return "非Admin用户"
  return decorated_view

添加Role Model

userinfo.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from app import login_manager
from app.db import Base,engine,session
from sqlalchemy import Column,String,Integer,create_engine
from sqlalchemy_utils.types.choice import ChoiceType
from flask_login import UserMixin
from permissions import ADMIN,ROLES
class User(Base,UserMixin):
  __tablename__ = "user"
  id = Column(Integer,primary_key=True)
  user = Column(String(16))
  password = Column(String(16))
  roles = Column(ChoiceType(ROLES),default=ADMIN)
@login_manager.user_loaded
def user_loaded(id):
  return session.query(User).filter_by(id=id).first()
Base.metadata.create_all(engine)

使用user_loader装饰器的回调函数非常重要,它将决定user对象是否在登录状态。试想只有Admin权限操作的事情,那么此用户是必需先登录,否则无法验证Admin权限。更多Flask-Login相关操作可参考《Flask框架Flask-Login用法

登录

验证用户与密码等是否正确,后执行Flask-Login登录操作,记录登录状态,验证用户权限

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from app import app
from flask import request
from flask_login import login_user
from flask_principal import current_app,identity_changed,Identity
from userinfo import User
from app.db import session
@app.route("/login",methods=["POST"])
def login():
  user = request.form.get("user",None)
  password = request.form.get("password",None)
  if not user or not password:
    ...
  user = session.query(User).filter_by(user=user,password=password).first()
  if not user:
    ...
  # 登录
  login_user(user)
  # 发送信号,载入用户权限
  identity_changed.send(current_app._get_current_object(),identity=Identity(user.id))
  return ...

identity_changed.send()函数会将sender:current_app._get_current_object()当前应用app和身份对象和identity:Identity(user.id)用户对象以信号的新式发送出去,开发者可以用identity_loaded.connect_via(app)接收信号,并载入权限

?
1
2
3
4
5
6
7
8
9
from flask_login import current_user
from flask_principal import identity_loaded,UserNeed,RoleNeed
@identity_loaded.connect_via(app)
def on_identity_loaded(sendder,identity):
  identity.user = current_user
  if hasattr(current_user,"id"):
    identity.provides.add(UserNeed(current_user.id))
  if hasattr(current_user,"roles"):
    identity.provides.add(RoleNeed(current_user.roles.code))

实现只有Admin权限用户才能操作删除用户

?
1
2
3
4
5
6
from app import app
from permission import admin_authority
@app.route("/delete_user",methods=["POST"])
@admin_authority
def delete_user():
  ...

希望本文所述对大家基于Flask框架的Python程序设计有所帮助。

原文链接:https://blog.csdn.net/y472360651/article/details/77498874