Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to modify a response in Flask with eg process_response

Tags:

python

flask

Given a simple Flask application, I'm just curious about whether there is a proper way to modify a Response in the hooks such as process_response?

e.g. Given:

from flask import Flask, Response

class MyFlask(Flask):
    def process_response(self, response):
        # edit response data, eg. add "... MORE!", but
        # keep eg mimetype, status_code
        response.data += "... This is added" # but should I modify `data`?
        return response
        # or should I:
        #     return Response(response.data + "... this is also added",
        #                     mimetype=response.mimetype, etc)

app = MyFlask(__name__)

@app.route('/')
def root():
    return "abddef"

if __name__ == '__main__':
    app.run()

Is it proper to just create a new response each time, or is it canonical to just edit in-place the response parameter and return that modified response?

This may be purely stylistic, but I'm curious – and I haven't noticed anything in my reading that would indicate the preferred way to do this (even though it's probably quite common).

Thanks for reading.

like image 512
Brian M. Hunt Avatar asked Nov 12 '11 15:11

Brian M. Hunt


People also ask

How do I send a custom response in Flask?

Typically a custom response class adds or changes the behavior of the default response class, so it is common to create these custom classes as subclasses of Flask's Response class. To tell Flask to use my custom response class, all I need to do is set my class in app. response_class .

How do you process incoming request data in Flask?

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.


1 Answers

From the Flask.process_response docs:

Can be overridden in order to modify the response object before it's sent to the WSGI server.

The response object is created on flask dispacher mechanism (Flask.full_dispatch_request). So if you want to create response objects under your own way, override Flask.make_reponse. Use Flask.process_response only when the desired modifications can be made using the created response object parameter.

like image 79
Carlo Pires Avatar answered Sep 22 '22 17:09

Carlo Pires