ba-thesis/backend/main.py

67 lines
1.9 KiB
Python
Raw Normal View History

2023-05-12 03:59:05 +01:00
import logging
2023-05-10 16:19:38 +01:00
2023-05-12 03:59:05 +01:00
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from . import crud, models, schemas
from.database import engine, SessionLocal
log = logging.getLogger()
models.Base.metadata.create_all(bind=engine)
2023-05-10 16:19:38 +01:00
app = FastAPI()
2023-05-12 03:59:05 +01:00
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
2023-05-10 16:19:38 +01:00
@app.get("/hello/")
2023-05-12 03:59:05 +01:00
def hello():
2023-05-10 16:19:38 +01:00
return "Hello World!"
2023-05-12 03:59:05 +01:00
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
existing_user = crud.read_user_by_email(db, email=user.email)
if existing_user:
raise HTTPException(status_code=400, detail="A user with this email address is already registered.")
return crud.create_user(db=db, user=user)
@app.get("/users/{id}", response_model=schemas.User)
def read_user(id: int, db: Session = Depends(get_db)):
user = crud.read_user(db=db, id=id)
if not user:
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
return user
@app.get("/users/", response_model=list[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
users = crud.read_users(db=db, skip=skip, limit=limit)
return users
@app.patch("/users/{id}", response_model=schemas.User)
def update_user(id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)):
current_user = crud.read_user(db=db, id=id)
if not current_user:
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
return crud.update_user(db=db, user=user, id=id)
@app.delete("/users/{id}", response_model=schemas.User)
def delete_user(id: int, db: Session = Depends(get_db)):
user = crud.read_user(db=db, id=id)
if not user:
raise HTTPException(status_code=404, detail=f"No user with id '{id}' found.")
return crud.delete_user(db=db, id=id)