skip to Main Content

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


  1. You have to use type="json" in the controller. It will go like the following:

    class MySuperController(http.Controller):
    
    @http.route('/devolive/review/<int:product_id>', type="json", method=['GET'])
    def get_review_data(self, product_id):
        return result
    

    This will always return the data in JSON format.

    Login or Signup to reply.
  2. 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:

     return http.response.........
    

    Instead you will do only this

     return self.build_result(result)
    

    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

     return result 
    

    Because odoo know that the result is json!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search