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

后端 未结 3 1740
暗喜
暗喜 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:35

    Set the header in a @app.after_request() hook, at which point you have a response object to set the header on:

    @app.after_request
    def apply_caching(response):
        response.headers["X-Frame-Options"] = "SAMEORIGIN"
        return response
    

    The flask.request context is still available when this hook runs, so you can still vary the response based on the request at this time.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-28 14:53

    We can set the response headers for all responses in Python Flask application gracefully using WSGI Middleware

    This way of setting response headers in Flask application context using middleware is thread safe and can be used to set custom & dynamic attributes, read the request headers this is especially helpful if we are setting custom/dynamic response headers from any helper class.

    file: middleware.py

    import flask
    from flask import request, g
    
    class SimpleMiddleWare(object):
        """
        Simple WSGI middleware
        """
    
        def __init__(self, app):
            self.app = app
            self._header_name = "any_request_header"
    
        def __call__(self, environ, start_response):
            """
            middleware to capture request header from incoming http request
            """
            request_id_header = environ.get(self._header_name)  # reading all request headers
            environ[self._header_name] = request_id_header  
    
            def new_start_response(status, response_headers, exc_info=None):
                """
                set custom response headers
                """
                # set the above captured request header as response header
                response_headers.append((self._header_name, request_id_header))
                # example to access flask.g values set in any class thats part of the Flask app & then set that as response header
                values = g.get(my_response_header, {})
                if values.get('x-custom-header'):
                    response_headers.append(('x-custom-header', values.get('x-custom-header')))
                return start_response(status, response_headers, exc_info)
    
            return self.app(environ, new_start_response)
    

    Calling the middleware from main class

    file : main.py

    from flask import Flask
    import asyncio
    from gevent.pywsgi import WSGIServer
    from middleware import SimpleMiddleWare
    
        app = Flask(__name__)
        app.wsgi_app = SimpleMiddleWare(app.wsgi_app)
    
    0 讨论(0)
提交回复
热议问题