From 128e30b8e9d4d0f8245416811316c02234c5480a Mon Sep 17 00:00:00 2001 From: Kyle Date: Fri, 4 Dec 2015 10:33:27 -0800 Subject: [PATCH] WSGI middleware should call "close" on iterable if available --- repoze/tm/__init__.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/repoze/tm/__init__.py b/repoze/tm/__init__.py index 4c5ee3f..422c9c2 100644 --- a/repoze/tm/__init__.py +++ b/repoze/tm/__init__.py @@ -36,7 +36,7 @@ def __init__(self, application, commit_veto=None): self.application = application self.commit_veto = commit_veto self.transaction = transaction # for testing - + def __call__(self, environ, start_response): transaction = self.transaction environ[ekey] = True @@ -47,8 +47,10 @@ def save_status_and_headers(status, headers, exc_info=None): ctx.update(status=status, headers=headers) return start_response(status, headers, exc_info) + iterable = None try: - for chunk in self.application(environ, save_status_and_headers): + iterable = self.application(environ, save_status_and_headers) + for chunk in iterable: yield chunk except Exception: """Saving the exception""" @@ -58,6 +60,18 @@ def save_status_and_headers(status, headers, exc_info=None): reraise(type_, value, tb) finally: del type_, value, tb + finally: + if hasattr(iterable, 'close'): + try: + iterable.close() + except Exception: + """Saving the exception""" + try: + type_, value, tb = sys.exc_info() + self.abort() + reraise(type_, value, tb) + finally: + del type_, value, tb # ZODB 3.8 + has isDoomed if hasattr(transaction, 'isDoomed') and transaction.isDoomed():