对于某些类型的应用程序,您可能希望向整个应用程序添加依赖项。
与向路径操作修饰器添加依赖项的方式类似,也可以将它们添加到应用程序中。FastAPI
在这种情况下,它们将应用于应用程序中的所有路径操作:

  1. from fastapi import Depends, FastAPI, Header, HTTPException
  2. async def verify_token(x_token: str = Header(...)):
  3. if x_token != "fake-super-secret-token":
  4. raise HTTPException(status_code=400, detail="X-Token header invalid")
  5. async def verify_key(x_key: str = Header(...)):
  6. if x_key != "fake-super-secret-key":
  7. raise HTTPException(status_code=400, detail="X-Key header invalid")
  8. return x_key
  9. app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
  10. @app.get("/items/")
  11. async def read_items():
  12. return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
  13. @app.get("/users/")
  14. async def read_users():
  15. return [{"username": "Rick"}, {"username": "Morty"}]

本节中有关向路径操作修饰器添加依赖项的所有想法仍然适用,但在这种情况下,适用于应用中的所有路径操作。

路径操作组的依赖项

稍后,当阅读如何构建更大的应用程序(更大的应用程序 - 多个文件),可能与多个文件,您将学习如何声明一个参数的一组路径操作。dependencies