feature: Das Anlegen doppelter Einträge muss mit der richtigen Fehlermeldung abgelehnt werden
Es darf kein Serverfehlersein.
This commit is contained in:
+19
-12
@@ -1,11 +1,13 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from sqlalchemy.exc import IntegrityError
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from sqlalchemy.exc import IntegrityError, DataError
|
||||||
from sqlmodel import Session, SQLModel, create_engine, select
|
from sqlmodel import Session, SQLModel, create_engine, select
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from api.models import Car, FuelItem
|
from api.models import Car, FuelItem
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -46,8 +48,9 @@ def fill_database():
|
|||||||
session.refresh(fill_item)
|
session.refresh(fill_item)
|
||||||
|
|
||||||
|
|
||||||
|
# noinspection PyUnusedLocal
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(actual_app: FastAPI):
|
||||||
# startup
|
# startup
|
||||||
create_db_and_tables()
|
create_db_and_tables()
|
||||||
try:
|
try:
|
||||||
@@ -60,13 +63,21 @@ async def lifespan(app: FastAPI):
|
|||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
|
|
||||||
|
def save_object(obj):
|
||||||
|
with Session(engine) as session:
|
||||||
|
try:
|
||||||
|
session.add(obj)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(obj)
|
||||||
|
return obj
|
||||||
|
except IntegrityError|DataError as e:
|
||||||
|
content = jsonable_encoder({"message": e})
|
||||||
|
return JSONResponse(content=content, status_code=400)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/cars/")
|
@app.post("/cars/")
|
||||||
def create_cars(car: Car):
|
def create_cars(car: Car):
|
||||||
with Session(engine) as session:
|
return save_object(car)
|
||||||
session.add(car)
|
|
||||||
session.commit()
|
|
||||||
session.refresh(car)
|
|
||||||
return car
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/cars/")
|
@app.get("/cars/")
|
||||||
@@ -78,11 +89,7 @@ def read_cars():
|
|||||||
|
|
||||||
@app.post("/fill_items/")
|
@app.post("/fill_items/")
|
||||||
def create_cars(fill_item: FuelItem):
|
def create_cars(fill_item: FuelItem):
|
||||||
with Session(engine) as session:
|
return save_object(fill_item)
|
||||||
session.add(fill_item)
|
|
||||||
session.commit()
|
|
||||||
session.refresh(fill_item)
|
|
||||||
return fill_item
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/fill_items/")
|
@app.get("/fill_items/")
|
||||||
|
|||||||
Reference in New Issue
Block a user