Python, Flask: How to set response header for all responses

后端 未结 3 1768
暗喜
暗喜 2020-12-28 14:16

I want to set all of my http headers responses to something like this:

response.headers[\"X-Frame-Options\"] = \"SAMEORIGIN\"

I checked thi

3条回答
  •  清歌不尽
    2020-12-28 14:41

    The @app.after_request() hook was not adequate for my use case.

    My use case is as follows: I have a google cloud function, and I want to set the CORS headers for all responses. There are possibly multiple responses, as I have to validate the input and return if there are issues with it, I have to process data and possibly return early if something fails etc. So I've created a helper function as follows:

    # Helper function to return a response with status code and CORS headers
    def prepare_response(res_object, status_code):
        response = flask.jsonify(res_object)
        response.headers.set('Access-Control-Allow-Origin', '*')
        response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
        return response, status_code
    

    Thus, when I want to return a response (always with CORS headers), I can now call this function and I do not duplicate the response.headers setup necessary to enable CORS.

提交回复
热议问题