Coverage for docs_src/sql_databases/sql_app_py39/main.py: 100%
34 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from fastapi import Depends, FastAPI, HTTPException 1abcd
2from sqlalchemy.orm import Session 1abcd
4from . import crud, models, schemas 1abcd
5from .database import SessionLocal, engine 1abcd
7models.Base.metadata.create_all(bind=engine) 1abcd
9app = FastAPI() 1abcd
12# Dependency
13def get_db(): 1abcd
14 db = SessionLocal() 1abcd
15 try: 1abcd
16 yield db 1abcd
17 finally:
18 db.close() 1abcd
21@app.post("/users/", response_model=schemas.User) 1abcd
22def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): 1abcd
23 db_user = crud.get_user_by_email(db, email=user.email) 1abcd
24 if db_user: 1abcd
25 raise HTTPException(status_code=400, detail="Email already registered") 1abcd
26 return crud.create_user(db=db, user=user) 1abcd
29@app.get("/users/", response_model=list[schemas.User]) 1abcd
30def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcd
31 users = crud.get_users(db, skip=skip, limit=limit) 1abcd
32 return users 1abcd
35@app.get("/users/{user_id}", response_model=schemas.User) 1abcd
36def read_user(user_id: int, db: Session = Depends(get_db)): 1abcd
37 db_user = crud.get_user(db, user_id=user_id) 1abcd
38 if db_user is None: 1abcd
39 raise HTTPException(status_code=404, detail="User not found") 1abcd
40 return db_user 1abcd
43@app.post("/users/{user_id}/items/", response_model=schemas.Item) 1abcd
44def create_item_for_user( 1abcd
45 user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
46):
47 return crud.create_user_item(db=db, item=item, user_id=user_id) 1abcd
50@app.get("/items/", response_model=list[schemas.Item]) 1abcd
51def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcd
52 items = crud.get_items(db, skip=skip, limit=limit) 1abcd
53 return items 1abcd