Debian Codegraph @

docs_src/dependencies/tutorial008d_an_py310.py

raw
1 from typing import Annotated
2
3 from fastapi import Depends, FastAPI, HTTPException
4
5 app = FastAPI()
6
7
8 class InternalError(Exception):
9 pass
10
11
12 def get_username():
13 try:
14 yield "Rick"
15 except InternalError:
16 print("We don't swallow the internal error here, we raise again 😎")
17 raise
18
19
20 @app.get("/items/{item_id}")
21 def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
22 if item_id == "portal-gun":
23 raise InternalError(
24 f"The portal gun is too dangerous to be owned by {username}"
25 )
26 if item_id != "plumbus":
27 raise HTTPException(
28 status_code=404, detail="Item not found, there's only a plumbus here"
29 )
30 return item_id