python FastAPI端点的装饰器WITH参数

3b6akqbq  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(140)

我请了一个装修师

def security(required_roles):
    def decorator(function):
        async def wrapper():
            print("ROLES", required_roles)
            return function
        return wrapper
    return decorator

这个端点,我想修饰一下:

@app.get(
    "/me", summary="Get details of currently logged in user", response_model=SystemUser
)
@security(required_roles=["role1", "role2"])
async def get_me(user: SystemUser = Depends(get_current_user)):
    return user

但当我叫它的时候,我得到的是:

File "/home/niels/PycharmProjects/fastApiProject/venv/lib/python3.10/site-packages/fastapi/routing.py", line 139, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for SystemUser
response
  value is not a valid dict (type=type_error.dict)

有人能告诉我为什么和如何重写装饰器吗?如果我把装饰器***放在***@app.get(...)之前,它不会被执行,也不知道为什么。任何帮助都将不胜感激。

w6lpcovy

w6lpcovy1#

您应该将 Package 器参数传递给 Package 的函数,并对其进行await

def security(required_roles):
    def decorator(function):
        async def wrapper(*args, **kwargs):
            print("ROLES", required_roles)
            return await function(*args, **kwargs)
        return wrapper
    return decorator

相关问题