This is my code:
@app.route(\'/hello\', methods=[\"POST\"])
def hello():
resp = make_response()
resp.headers[\'Access-Control-Allow-Origin\'] = \'*\'
We can set the response headers in Python Flask application using Flask application context using flask.g
This way of setting response headers in Flask application context using flask.g is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g is global & valid for that request thread only.
Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.
Sample Code: file: helper.py
import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession
def _extract_response_header(response)
"""
extracts response headers from response object
and stores that required response header in flask.g app context
"""
headers = CIMultiDict(response.headers)
if 'my_response_header' not in g:
g.my_response_header= {}
g.my_response_header['x-custom-header'] = headers['x-custom-header']
async def call_post_api(post_body):
"""
sample method to make post api call using aiohttp clientsession
"""
try:
async with ClientSession() as session:
async with session.post(uri, headers=_headers, json=post_body) as response:
responseResult = await response.read()
_extract_headers(response, responseResult)
response_text = await response.text()
except (HttpTimeout, ConnectionError) as ex:
raise HttpTimeout(exception_message)
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)
environ[self._header_name] = request_id_header
def new_start_response(status, response_headers, exc_info=None):
"""
set custom response headers
"""
# set the request header as response header
response_headers.append((self._header_name, request_id_header))
# this is trying to access flask.g values set in helper class & 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)