使用uuid生成token放入缓存中
通过g对象跨函数传参
init.py
from flask_restful import Api
from App.apis.blog_api import BlogsResource
api = Api()
def init_api(app):
api.init_app(app)
api.add_resource(BlogsResource, "/blogs/")
decorator.py
from flask import request, g
from flask_restful import abort
from App.extension import cache
from App.models.user_model import User
def login_required(fun):
def wrapper(*args, **kwargs):
token = request.args.get("token")
if not token:
abort(400, msg="请提供令牌")
user_id = cache.get(token)
if not user_id:
abort(400, msg="用户状态失效")
user = User.query.get(user_id)
if not user:
abort(400, msg="用户不存在")
g.user = user
return fun(*args, **kwargs)
return wrapper
def permission_required(permission):
def login_required(fun):
def wrapper(*args, **kwargs):
token = request.args.get("token")
if not token:
abort(400, msg="请提供令牌")
user_id = cache.get(token)
if not user_id:
abort(400, msg="用户状态失效")
user = User.query.get(user_id)
if not user:
abort(400, msg="用户不存在")
if not user.check_permission(permission):
abort(403, msg="can't access")
g.user = user
return fun(*args, **kwargs)
return wrapper
return login_required
blog_api.py
from flask import g
from flask_restful import Resource
from App.apis.user_decorator import login_required, permission_required
from App.models.student_model import Student1
class BlogsResource(Resource):
@login_required
def get(self):
data = {
"msg": "ok",
"status": 200
}
return data
@permission_required("WRITE")
def post(self):
user = g.user
print(user.u_name)
data = {
"msg": "ok",
"status": 200
}
return data