What I know:
We all know that flask has a useful query.get_or_404
we can call it to any class object and return the object or raise a 404 error if the object is not found.
The problem:
I have a very large application and using that function for my queries, but it becomes now a bit confusing when I'm sending data to the front end and other application consuming my APIs. When an object they are querying is not found it returns 404 and the same behavior happens also when a page is not found.
What I want to achieve:
I would like to have a meaningful response that is different for every object that is not found, and different for the normal 404 error message.
Example :
if I have this query:
user = User.query.get_or_404(id)
if the user is not found I want to raise an HTTP error and return a message like user not found
What I have tried So far:
user = User.query.get(id)
if user:
#do something
else
return {'status':'01', 'description': 'user not found'}
# or raise a http error
The problem with this approach I can't maintain the application I'm working on, it will require me to change everywhere I was using get_or_404 with that code.
What I'm thinking about :
Creating a function like query.get_or_404
but with another status message
like query.get_or_415
for example and add an error handler for 415 HTTP code so that if an object is not found it can return {'status':'0message:ge : 'object of the class is not found'}
How can I achieve it?
I have checked for that function in Flask but was unable to find it
Anyone with suggestions?
BaseQuery
and pass it toSQLAlchemy
. – Opportunist