If there a way to set the response type for a whole method and/or controller in Odoo ?
I created custom controllers to return data formatted as json
. The problem is when the data isn’t found I receive a classic 404 page instead of a json formatted result.
Of course I could set the content_type of the response but I don’t like it. The code clarity get worse because I have to repeat the content_type settings
multiple times in my controllers.
This should be managed with a decorator, no?
class MySuperController(http.Controller):
@http.route('/devolive/review/<int:product_id>', method=['GET'])
def get_review_data(self, product_id):
#...
if check:
raise http.NotFound() # Going to show a normal 404 page.
#...
return http.Response(json.dumps(result, default=json_default), content_type='application/json')
2
Answers
You have to use type="json" in the controller. It will go like the following:
This will always return the data in JSON format.
Here is good example of DTY principle:
Just creat a method to build response with the ugly code and call it, you will even minimize having to write each time:
Instead you will do only this
Inside that method chose what to do with the result if it’s not found.
Also why not using the recommendation of odoo to make the controller handle json request instead of http like this, because if you do so you will write only
Because odoo know that the result is json!