Coverage for docs_src/dependencies/tutorial008b_an.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from fastapi import Depends, FastAPI, HTTPException 1abcde

2from typing_extensions import Annotated 1abcde

3 

4app = FastAPI() 1abcde

5 

6 

7data = { 1abcde

8 "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, 

9 "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, 

10} 

11 

12 

13class OwnerError(Exception): 1abcde

14 pass 1abcde

15 

16 

17def get_username(): 1abcde

18 try: 1abcde

19 yield "Rick" 1abcde

20 except OwnerError as e: 1abcde

21 raise HTTPException(status_code=400, detail=f"Owner error: {e}") 1abcde

22 

23 

24@app.get("/items/{item_id}") 1abcde

25def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): 1abcde

26 if item_id not in data: 1abcde

27 raise HTTPException(status_code=404, detail="Item not found") 1abcde

28 item = data[item_id] 1abcde

29 if item["owner"] != username: 1abcde

30 raise OwnerError(username) 1abcde

31 return item 1abcde