Estoy tratando de registrar datos en Flask Middleware. Uso una función process_response para registrar los datos de respuesta.
Tengo este bloque de código en el que intento inyectar la duración del tiempo en los encabezados de la respuesta. Sin embargo X-Time-Taken no se agrega al encabezado. El encabezado de respuesta es el encabezado request header: Content-Type: text/plain; charset=utf-8 .
¿Por qué no se agrega X-Time-Taken al encabezado?
Para su información, estoy basando mi código en esto , lo que sugiere que lo que estoy haciendo debería funcionar.
class SampleWSGI(): def __init__(self, app, config=None): self.app = app self.app_id = config["app_id"] self.secret_key = config["secret_key"] def __call__(self, environ, start_response): request = Request(environ) resp = Response(start_response) self._process_response(self.app_id, resp) apikey = request.args.get("apikey") if "favicon.ico" in request.path: return x = self.authorize_user(apikey=apikey, client_path=request.path) if x.status_code < 400: ##Injects duration into response time start_time = datetime.utcnow().timestamp() def injecting_start_response(status, headers, exc_info=None): end_time = datetime.utcnow().timestamp() time_taken = str(end_time - start_time) headers.append(('X-Time-Taken', time_taken)) return start_response(status, headers, exc_info) return self.app(environ, injecting_start_response) res = Response(u'Authorization failed', mimetype= 'text/plain', status=x.status_code) return res(environ, start_response) @staticmethod def _process_response(app_id, response, request): #req = Request(environ, shallow=True) print(f'request header: {response.headers}')Prueba lo siguiente:
class SampleWSGI(): def __init__(self, app, config=None): self.app = app self.app_id = config["app_id"] self.secret_key = config["secret_key"] def __call__(self, environ, start_response): request = Request(environ) resp = Response(start_response) # This line changed: self._process_response(self.app_id, resp, request) apikey = request.args.get("apikey") if "favicon.ico" in request.path: return x = self.authorize_user(apikey=apikey, client_path=request.path) if x.status_code < 400: ##Injects duration into response time start_time = datetime.utcnow().timestamp() def injecting_start_response(status, headers, exc_info=None): end_time = datetime.utcnow().timestamp() time_taken = str(end_time - start_time) headers.append(('X-Time-Taken', time_taken)) return start_response(status, headers, exc_info) return self.app(environ, injecting_start_response) res = Response(u'Authorization failed', mimetype= 'text/plain', status=x.status_code) return res(environ, start_response) @staticmethod def _process_response(app_id, response, request): #req = Request(environ, shallow=True) print(f'request header: {response.headers}') Como puede ver, no pasó la request a _process_response() . Los errores simples nos ahuyentan a todos, lamentablemente...