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

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-06 08:24 +0000

1from fastapi import Depends, FastAPI, HTTPException 1abcdef

2from typing_extensions import Annotated 1abcdef

3 

4app = FastAPI() 1abcdef

5 

6 

7data = { 1abcdef

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

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

10} 

11 

12 

13class OwnerError(Exception): 1abcdef

14 pass 1abcdef

15 

16 

17def get_username(): 1abcdef

18 try: 1msgnthouipvjqwkrxl

19 yield "Rick" 1msgnthouipvjqwkrxl

20 except OwnerError as e: 1sgthuivjwkxl

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

22 

23 

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

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

26 if item_id not in data: 1msgnthouipvjqwkrxl

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

28 item = data[item_id] 1mgnhoipjqkrl

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

30 raise OwnerError(username) 1ghijkl

31 return item 1mnopqr