SoFunction
Updated on 2024-11-20

Flask framework Flask-Principal basic usage example analysis

This article example describes the Flask framework Flask-Principal basic usage. Shared for your reference, as follows:

Flask-Principal is an extension to the Flask framework, the main principal pieces are Identity, Needs, Permission and IdentityContext.

  • Identity: represents the user, stores and loads each request from various locations, and contains the access rights that the user has.
  • Needs: Requirements are the minimum granularity of access control and represent the specific parameters of this situation. For example: managing users, being able to edit posts .
  • Permission: Permissions
  • IdentityContext: Context specific to a permission, can be used as a context manager or decorator

mounting

pip install flask-principal

initialization

from flask_principal import Principal
principal = Principal()
principal.init_app(app)

Rights Management

from flask-principal import Permission,RoleNeed
from functools import wraps
# Define relevant roles
NORMAL = "NORMAL"
ADMIN = "ADMIN"
ROLES = (
  ("NORMAL","Ordinary users"),
  ("ADMIN","Administrator")
)
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 "Non-Admin users"
  return decorated_view

Add Role Model

from app import login_manager
from  import Base,engine,session
from sqlalchemy import Column,String,Integer,create_engine
from sqlalchemy_utils. 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 (User).filter_by(id=id).first()
.create_all(engine)

utilizationuser_loaderThe callback function of the decorator is very important as it will determine whether the user object is in the logged in state or not. Imagine something that only Admin rights can do, then this user is required to be logged in first, otherwise Admin rights cannot be verified. More...Flask-LoginRelated operations can be found in theFlask Framework Flask-Login Usage

log in

Verify that the user, password, etc. are correct, and then execute theFlask-LoginLogin operation, record login status, verify user rights

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  import session
@("/login",methods=["POST"])
def login():
  user = ("user",None)
  password = ("password",None)
  if not user or not password:
    ...
  user = (User).filter_by(user=user,password=password).first()
  if not user:
    ...
  # Login
  login_user(user)
  # Send a signal to load user rights
  identity_changed.send(current_app._get_current_object(),identity=Identity())
  return ...

identity_changed.send()function displays thesender:current_app._get_current_object()The current application app and identity object andidentity:Identity()User objects are sent out in a new style of signaling, and developers can use theidentity_loaded.connect_via(app)Receiving signals and loading permissions

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):
   = current_user
  if hasattr(current_user,"id"):
    (UserNeed(current_user.id))
  if hasattr(current_user,"roles"):
    (RoleNeed(current_user.))

Realize that only users with Admin rights can delete users.

from app import app
from permission import admin_authority
@("/delete_user",methods=["POST"])
@admin_authority
def delete_user():
  ...

We hope that what we have described in this article will help you in designing Python programs based on Flask framework.