Coverage for docs_src/sql_databases/sql_app/alt_main.py: 100%
40 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 typing import List 1abcde
3from fastapi import Depends, FastAPI, HTTPException, Request, Response 1abcde
4from sqlalchemy.orm import Session 1abcde
6from . import crud, models, schemas 1abcde
7from .database import SessionLocal, engine 1abcde
9models.Base.metadata.create_all(bind=engine) 1abcde
11app = FastAPI() 1abcde
14@app.middleware("http") 1abcde
15async def db_session_middleware(request: Request, call_next): 1abcde
16 response = Response("Internal server error", status_code=500) 1abcde
17 try: 1abcde
18 request.state.db = SessionLocal() 1abcde
19 response = await call_next(request) 1abcde
20 finally:
21 request.state.db.close() 1abcde
22 return response 1abcde
25# Dependency
26def get_db(request: Request): 1abcde
27 return request.state.db 1abcde
30@app.post("/users/", response_model=schemas.User) 1abcde
31def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): 1abcde
32 db_user = crud.get_user_by_email(db, email=user.email) 1abcde
33 if db_user: 1abcde
34 raise HTTPException(status_code=400, detail="Email already registered") 1abcde
35 return crud.create_user(db=db, user=user) 1abcde
38@app.get("/users/", response_model=List[schemas.User]) 1abcde
39def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcde
40 users = crud.get_users(db, skip=skip, limit=limit) 1abcde
41 return users 1abcde
44@app.get("/users/{user_id}", response_model=schemas.User) 1abcde
45def read_user(user_id: int, db: Session = Depends(get_db)): 1abcde
46 db_user = crud.get_user(db, user_id=user_id) 1abcde
47 if db_user is None: 1abcde
48 raise HTTPException(status_code=404, detail="User not found") 1abcde
49 return db_user 1abcde
52@app.post("/users/{user_id}/items/", response_model=schemas.Item) 1abcde
53def create_item_for_user( 1abcde
54 user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
55):
56 return crud.create_user_item(db=db, item=item, user_id=user_id) 1abcde
59@app.get("/items/", response_model=List[schemas.Item]) 1abcde
60def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): 1abcde
61 items = crud.get_items(db, skip=skip, limit=limit) 1abcde
62 return items 1abcde