17

I know that Response is what Flask uses by default for http responses. For specific responses format, I usually use make_response. Are there any specific cases where we have to use flask.Response instead of flask.make_response? in other words, does flask.make_response work in all situations or sometimes flask.Response is the only or the better alternative? Thanks!

ettanany
  • 19,038
  • 9
  • 47
  • 63

1 Answers1

37

make_response() gives you a convenience interface, one that will take arguments in more formats than the flask.Response() object takes.

In addition, make_response() uses the Flask.response_class attribute (so app.response_class) to build the response. The default value for Flask.response_class is flask.Response, but you can set this value to a subclass instead.

So you should really always use make_response(), rather than use flask.Response() directly, especially if you want to support swapping out what Response class you actually use for responses.

You may have to use app.response_class directly if it is a subclass that takes arguments that make_response() can't supply.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Thank you for this useful answer. I would appreciate it if you can provide some example when I have to use `app.response_class` that you mentioned in the last part of your answer. – ettanany Oct 24 '16 at 12:32
  • 2
    @ettanany: well, `Response()` takes specific arguments, all of which `make_response()` can normally supply. But if you created a subclass that takes more arguments, `make_response()` won't know about those. So that's a reason then to use the class directly, the only reason that I can think of here. – Martijn Pieters Oct 24 '16 at 12:34
  • I understand. Thank you! – ettanany Oct 24 '16 at 12:58
  • Does calling return jsonify(something) automatically call make_response? If not, then what is purpose of make_response when jsonify also can be used to return data to caller – variable Nov 05 '19 at 10:57
  • @variable: You are asking a lot of questions in comments. You can trivially answer your question by looking at the [documentation for `jsonify`](https://flask.palletsprojects.com/en/1.1.x/api/#flask.json.jsonify) and trying to think about what kind of responses might not return JSON to know what `make_response()` could be useful when *not* producing a JSON response. – Martijn Pieters Nov 05 '19 at 14:04