import HTTPException
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
在出错的地方直接 raise
抛出异常并转向
如果是在Dependency Injection中,用来判断登录、检查权限等,可以在抛出重定向的异常,这个使用headers实现
@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
if item_id not in items:
raise HTTPException(
status_code=307,
detail="Item not found",
headers={"Location": "the_url"},
)
return {"item": items[item_id]}
把 status_code 设置为307
然后设置 headers = {‘Location’: ‘the_redirect_url’}
就能实现重定向了,比如,如果没有登录,重定向为login等