diff --git a/sentry_sdk/integrations/flask.py b/sentry_sdk/integrations/flask.py index 975b776f3e..196f92bc2a 100644 --- a/sentry_sdk/integrations/flask.py +++ b/sentry_sdk/integrations/flask.py @@ -156,6 +156,7 @@ def _request_started(app, **kwargs): def _request_finished(sender, response, **kwargs): + # type: (Flask, Any, **Any) -> None # Manually close the transaction because Flask does not call `close()` on the WSGI response finish_running_transaction() diff --git a/sentry_sdk/integrations/wsgi.py b/sentry_sdk/integrations/wsgi.py index 42700a0c02..780beeb69a 100644 --- a/sentry_sdk/integrations/wsgi.py +++ b/sentry_sdk/integrations/wsgi.py @@ -257,21 +257,24 @@ def __iter__(self): # type: () -> Iterator[bytes] iterator = iter(self._response) - while True: - with use_isolation_scope(self._isolation_scope): - with use_scope(self._current_scope): - try: - chunk = next(iterator) - except StopIteration: - # Close the Sentry transaction (it could be that response.close() is never called by the framework) - # This is done here to make sure the Transaction stays - # open until all streaming responses are done. - finish_running_transaction() - break - except BaseException: - reraise(*_capture_exception()) + try: + while True: + with use_isolation_scope(self._isolation_scope): + with use_scope(self._current_scope): + try: + chunk = next(iterator) + except StopIteration: + break + except BaseException: + reraise(*_capture_exception()) + + yield chunk - yield chunk + finally: + # Close the Sentry transaction (it could be that response.close() is never called by the framework) + # This is done here to make sure the Transaction stays + # open until all streaming responses are done. + finish_running_transaction(self._current_scope) def close(self): # type: () -> None diff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py index cd4e71528c..90656698f9 100644 --- a/sentry_sdk/tracing_utils.py +++ b/sentry_sdk/tracing_utils.py @@ -726,9 +726,9 @@ def get_current_span(scope=None): from sentry_sdk.tracing import Span -def finish_running_transaction(): - # type: () -> None - current_scope = sentry_sdk.get_current_scope() +def finish_running_transaction(scope): + # type: (Optional[sentry_sdk.Scope]) -> None + current_scope = scope or sentry_sdk.get_current_scope() if current_scope.transaction is not None and hasattr( current_scope.transaction, "_context_manager_state" ):