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

18 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from fastapi import Depends, FastAPI, HTTPException 1abc

2 

3app = FastAPI() 1abc

4 

5 

6data = { 1abc

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

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

9} 

10 

11 

12class OwnerError(Exception): 1abc

13 pass 1abc

14 

15 

16def get_username(): 1abc

17 try: 1gjdhkeilf

18 yield "Rick" 1gjdhkeilf

19 except OwnerError as e: 1jdkelf

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

21 

22 

23@app.get("/items/{item_id}") 1abc

24def get_item(item_id: str, username: str = Depends(get_username)): 1abc

25 if item_id not in data: 1gjdhkeilf

26 raise HTTPException(status_code=404, detail="Item not found") 1jkl

27 item = data[item_id] 1gdheif

28 if item["owner"] != username: 1gdheif

29 raise OwnerError(username) 1def

30 return item 1ghi