其他分享
首页 > 其他分享> > Flask 学习-32.flask_jwt_extended 自定义装饰器

Flask 学习-32.flask_jwt_extended 自定义装饰器

作者:互联网

前言

创建自己的装饰器来扩展此扩展提供的装饰器的功能。例如,您可能想要创建自己的装饰器来验证 JWT 是否存在以及验证当前用户是否是管理员。

自定义装饰器

flask_jwt_extended.verify_jwt_in_request()可用于构建您自己的装饰器。这与 . 使用的功能相同flask_jwt_extended.jwt_required()。

官方文档示例

from functools import wraps

from flask import Flask
from flask import jsonify

from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt
from flask_jwt_extended import JWTManager
from flask_jwt_extended import verify_jwt_in_request

app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)


# Here is a custom decorator that verifies the JWT is present in the request,
# as well as insuring that the JWT has a claim indicating that this user is
# an administrator
def admin_required():
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            verify_jwt_in_request()
            claims = get_jwt()
            if claims["is_administrator"]:
                return fn(*args, **kwargs)
            else:
                return jsonify(msg="Admins only!"), 403

        return decorator

    return wrapper


@app.route("/login", methods=["POST"])
def login():
    access_token = create_access_token(
        "admin_user", additional_claims={"is_administrator": True}
    )
    return jsonify(access_token=access_token)


@app.route("/protected", methods=["GET"])
@admin_required()
def protected():
    return jsonify(foo="bar")


if __name__ == "__main__":
    app.run()

标签:__,extended,return,自定义,Flask,jwt,flask,import
来源: https://www.cnblogs.com/yoyoketang/p/16646158.html