Qual è il modo appropriato per intercettare WSGI start_response?
-
24-09-2019 - |
Domanda
Ho WSGI middleware che ha bisogno di catturare lo stato HTTP (ad esempio 200 OK
) che strati interni di rendimento middleware chiamando start_response
. Attualmente sto facendo quanto segue, ma abusando di una lista non sembra essere la soluzione “giusta” per me:
class TransactionalMiddlewareInterface(object): def __init__(self, application, **config): self.application = application self.config = config def __call__(self, environ, start_response): status = [] def local_start(stat_str, headers=[]): status.append(int(stat_str.split(' ')[0])) return start_response(stat_str, headers) try: result = self.application(environ, local_start) finally: status = status[0] if status else 0 if status > 199 and status
La ragione per l'abuso lista è che non posso assegnare un nuovo valore per lo spazio dei nomi genitore all'interno di una funzione situate interamente.
Soluzione
È possibile assegnare lo status di un campo iniettato della funzione local_start
stesso, piuttosto che utilizzando l'elenco status
. Ho usato qualcosa di simile, funziona bene:
class TransactionalMiddlewareInterface(object):
def __init__(self, application, **config):
self.application = application
self.config = config
def __call__(self, environ, start_response):
def local_start(stat_str, headers=[]):
local_start.status = int(stat_str.split(' ')[0])
return start_response(stat_str, headers)
try:
result = self.application(environ, local_start)
finally:
if local_start.status and local_start.status > 199:
pass
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow