Coverage for docs_src/sql_databases/sql_app/main.py: 100%

35 statements  

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

1from typing import List 1abcde

2 

3from fastapi import Depends, FastAPI, HTTPException 1abcde

4from sqlalchemy.orm import Session 1abcde

5 

6from . import crud, models, schemas 1abcde

7from .database import SessionLocal, engine 1abcde

8 

9models.Base.metadata.create_all(bind=engine) 1abcde

10 

11app = FastAPI() 1abcde

12 

13 

14# Dependency 

15def get_db(): 1abcde

16 db = SessionLocal() 1abcde

17 try: 1abcde

18 yield db 1abcde

19 finally: 

20 db.close() 1abcde

21 

22 

23@app.post("/users/", response_model=schemas.User) 1abcde

24def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): 1abcde

25 db_user = crud.get_user_by_email(db, email=user.email) 1abcde

26 if db_user: 1abcde

27 raise HTTPException(status_code=400, detail="Email already registered") 1abcde

28 return crud.create_user(db=db, user=user) 1abcde

29 

30 

31@app.get("/users/", response_model=List[schemas.User]) 1abcde

32def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcde

33 users = crud.get_users(db, skip=skip, limit=limit) 1abcde

34 return users 1abcde

35 

36 

37@app.get("/users/{user_id}", response_model=schemas.User) 1abcde

38def read_user(user_id: int, db: Session = Depends(get_db)): 1abcde

39 db_user = crud.get_user(db, user_id=user_id) 1abcde

40 if db_user is None: 1abcde

41 raise HTTPException(status_code=404, detail="User not found") 1abcde

42 return db_user 1abcde

43 

44 

45@app.post("/users/{user_id}/items/", response_model=schemas.Item) 1abcde

46def create_item_for_user( 1abcde

47 user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) 

48): 

49 return crud.create_user_item(db=db, item=item, user_id=user_id) 1abcde

50 

51 

52@app.get("/items/", response_model=List[schemas.Item]) 1abcde

53def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcde

54 items = crud.get_items(db, skip=skip, limit=limit) 1abcde

55 return items 1abcde