Skip to content

Commit

Permalink
#188620653: wrap response to support trigger "close" (#73)
Browse files Browse the repository at this point in the history
* wrap response to support trigger close

* bump version remove extra logging
  • Loading branch information
xinghengwang authored Dec 4, 2024
1 parent df5843f commit f88cc9f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 7 deletions.
16 changes: 14 additions & 2 deletions examples/flask/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def mask_event(eventmodel):
'GET_METADATA': get_metadata,
'CAPTURE_OUTGOING_REQUESTS': False,
}

app.wsgi_app = MoesifMiddleware(app.wsgi_app, moesif_settings)

@app.route('/')
Expand All @@ -53,7 +54,12 @@ def index():

@app.route('/hello')
def hello():
return 'Hello, world'
# Create a response object
response = Response('Hello, world')

# Attach a function to call_on_close
response.call_on_close(lambda: print("Response has been sent to the client."))
return response;

@app.route('/user/<username>')
def show_user_profile(username):
Expand All @@ -80,10 +86,16 @@ def show_post(post_id):
}
]

@app.route('/error', methods=['GET'])
def error():
raise ValueError("This is a test error!")

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
json_body = json.dumps({'tasks': tasks})
return Response(response=json_body, status=201, mimetype='application/json')
response = Response(response=json_body, status=201, mimetype='application/json')
response.call_on_close(lambda: print("Response has been sent to the client."));
return response


@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
Expand Down
26 changes: 23 additions & 3 deletions moesifwsgi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def initialize_config(self):
response_catcher = HttpResponseCatcher(self.DEBUG)
self.api_client.http_call_back = response_catcher
Configuration.BASE_URI = self.settings.get("BASE_URI") or self.settings.get("LOCAL_MOESIF_BASEURL", "https://api.moesif.net")
Configuration.version = "moesifwsgi-python/1.9.7"
Configuration.version = "moesifwsgi-python/1.9.8"
if self.settings.get("CAPTURE_OUTGOING_REQUESTS", False):
StartCapture().start_capture_outgoing(self.settings)

Expand Down Expand Up @@ -172,7 +172,8 @@ def _start_response(status, response_headers, *args):
blocked_by = governed_response['blocked_by']
else:
# trigger next step in the process
response_chunks = event_info.finish_response(self.app(environ, _start_response))
original_response = self.app(environ, _start_response);
response_chunks = event_info.finish_response(original_response)

# Add response chunks and response headers to the environ
environ["moesif.response_body_chunks"] = response_chunks
Expand All @@ -186,10 +187,29 @@ def _start_response(status, response_headers, *args):
self.add_user_and_metadata(event_info, environ, response_headers_mapping)

try:
return response_chunks
return self.wrap_response(response_chunks, original_response)
finally:
self.process_and_add_event_if_required(event_info, environ, response_headers_mapping, blocked_by)

def wrap_response(self, response_chunks, original_response):
class WrappedResponse:
def __init__(self, chunks, original):
self.chunks = chunks
self.original = original

def __iter__(self):
return iter(self.chunks)

def close(self):
if hasattr(self.original, 'close'):
self.original.close()

def __getattr__(self, name):
# Delegate attribute access to the original response
return getattr(self.original, name)

return WrappedResponse(response_chunks, original_response)

def prepare_event_info(self, environ, start_response, request_time):
event_info = DataHolder(
self.settings.get("DISABLED_TRANSACTION_ID", False),
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.9.7',
version='1.9.8',

description='Moesif Middleware for Python WSGI based platforms (Flask, Bottle & Others)',
long_description=long_description,
Expand All @@ -39,7 +39,7 @@

# Author details
author='Moesif, Inc',
author_email='xing@moesif.com',
author_email='team@moesif.com',

license='Apache Software License',

Expand Down

0 comments on commit f88cc9f

Please sign in to comment.