In our app there is a view that accepts an instance of a model as an argument, and if the request data misses some fields, the view does not get called, eg:
class Item(BaseModel):
id: int
price: float
is_offer: bool | None = False
@app.post("/")
async def hello_root(item: Item):
return dict(item)
This was fine for quite a while, but now we need to add the item to the database even if some of the fields are missing, but we still need to be able to tell that the item is invalid so we don't do some other logic with it.
The problem is that if the item is invalid, the view does not get called at all. Also, we can't replace item: Item
with item: dict
in the view function signature for historic reasons.
I tried adding a custom exception handler, but then it applies for all the views and I would have to figure out which view would have been called, and then reuse some logic from this particular one, and getting the item data is not that straightforward either:
@app.exception_handler(RequestValidationError)
async def req_validation_handler(request, exc):
print("We got an error")
...
My other idea was to create some sort of a custom field that could be nullable, but at the same time have a flag as to whether it is required or not which could be checked inside our view, but I still haven't figured out how to do that.
Is there a proper way of doing this?