[Python] How to handle database commit errors in FastAPI

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I'm putting together an api to record weather readings from a Raspberry Pico. What I need help with is error handling. The code shown here technically is trapping the error and sending back a response that there was an error, but it is really not doing it correctly.

    First, I need to have it send back the actual error. I would have thought it would be easy to pull that out of e but I'm not able to.

    Next, this sends back a 200 OK code and that is not good. I need to send back the proper code when something fails on the server side. I don't know what that proper code should be nor do I know how to send that back so I could use some help here as well.

    Finally, is doing a rollback all I need to do here? Should I be closing the session? That being said, should I be closing the session in general if things go well?

    @app.post("/reading")
    async def record_reading(sensor_id: int, fahrenheit: float, pressure: float, humidity: float, dew_point: float, battery: float):
    weather_reading = WeatherReading(
    sensor_id = sensor_id,
    fahrenheit = fahrenheit,
    pressure = pressure,
    humidity = humidity,
    dew_point = dew_point,
    battery = battery
    )
    try:
    session.add(weather_reading)
    session.commit()
    return {"reading added"}
    except SQLAlchemyError as e:
    session.rollback()
    return {"Error during commit"}

    Continue reading...

Compartilhe esta Página