import HTTPException

  1. from fastapi import FastAPI, HTTPException
  2. app = FastAPI()
  3. items = {"foo": "The Foo Wrestlers"}
  4. @app.get("/items/{item_id}")
  5. async def read_item(item_id: str):
  6. if item_id not in items:
  7. raise HTTPException(status_code=404, detail="Item not found")
  8. return {"item": items[item_id]}

在出错的地方直接 raise

抛出异常并转向

如果是在Dependency Injection中,用来判断登录、检查权限等,可以在抛出重定向的异常,这个使用headers实现

  1. @app.get("/items-header/{item_id}")
  2. async def read_item_header(item_id: str):
  3. if item_id not in items:
  4. raise HTTPException(
  5. status_code=307,
  6. detail="Item not found",
  7. headers={"Location": "the_url"},
  8. )
  9. return {"item": items[item_id]}

把 status_code 设置为307
然后设置 headers = {‘Location’: ‘the_redirect_url’}
就能实现重定向了,比如,如果没有登录,重定向为login等