Quelle est la manière appropriée pour intercepter WSGI start_response?
-
24-09-2019 - |
Question
Je middleware WSGI qui a besoin de capter l'état HTTP (par exemple 200 OK
) que les couches internes de retour de middleware en appelant start_response
. Actuellement, je fais ce qui suit, mais en abusant d'une liste ne semble pas être la « bonne » solution pour moi:
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 raison de l'abus de liste est que je ne peux pas attribuer une nouvelle valeur à l'espace de noms de parent dans une fonction entièrement contenu.
La solution
Vous pouvez attribuer le statut de la fonction de champ de local_start
injecté lui-même plutôt que d'utiliser la liste des status
. J'ai utilisé quelque chose de similaire, fonctionne très bien:
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow