Tom*_*Mac 6 python authentication python-3.x fastapi
我在 Fastapi 身份验证中看到了两种不同的使用dependent的方法:
方法一:
@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
return user
Run Code Online (Sandbox Code Playgroud)
和方法2:
@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
return user
Run Code Online (Sandbox Code Playgroud)
方法 1 和方法 2 之间有什么区别?哪种方法更适合保护 API(即需要身份验证)?
正如 @Omer Alkin 正确指出的那样,当我们想要使用其返回值(用户或令牌或其他)时,需要在路径操作参数列表中指定依赖项。这是文档中的示例:
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
Run Code Online (Sandbox Code Playgroud)
如果依赖的返回值对我们来说并不重要或者没有返回,而只是一个副作用很重要,例如依赖抛出异常,那么我们可以在路径操作装饰器中指定依赖。
在这种情况下,我们还可以立即执行一组操作的依赖关系(进行身份验证),使用APIRouter
:
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
Run Code Online (Sandbox Code Playgroud)
还应该注意的是,您可以在路径操作或其子依赖项中重用相同的依赖项,因为 FastAPI默认实现缓存策略:
如果针对同一路径操作多次声明其中一个依赖项,例如,多个依赖项具有共同的子依赖项,则 FastAPI 将知道每个请求仅调用该子依赖项一次。
归档时间: |
|
查看次数: |
10643 次 |
最近记录: |