Debian Codegraph @

docs_src/dependencies/tutorial008d_py310.py

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