Skip to content

Instantly share code, notes, and snippets.

@TheBigRoomXXL
Last active May 12, 2023 14:35
Show Gist options
  • Save TheBigRoomXXL/d3af657623e3eac0497b47e4be84929b to your computer and use it in GitHub Desktop.
Save TheBigRoomXXL/d3af657623e3eac0497b47e4be84929b to your computer and use it in GitHub Desktop.
Post Processing Decorator for Flask Smorest - Execute a function after Flask returns response
class PostProcessingTask:
def __init__(self, func: Callable[..., None], *args: Any, **kwargs: Any):
self.func = func
self.args = args
self.kwargs = kwargs
def execute(self) -> None:
self.func(*self.args, **self.kwargs)
def post_processing(response: Response) -> Response:
"""Provide a way to execute a function AFTER the request has been returned by setting
request.post_processing with a PostProcessingTask object.
This is achieved with Werkzeug 'call_on_close' callback on response objects.
Unlike @app.after_response it:
- is not meant to modify the request object.
- trully happen after the request so you don't extend the request delay.
- won't affect the response if it raise an exception.
WARNING: if abort is called or an exception is raised during the view execution then the
post-processing won't happen.
WARNING: No request context or app context available when the request is executed.
for more technical details and context checkout:
https://stackoverflow.com/questions/48994440/execute-a-function-after-flask-returns-response
"""
if hasattr(request, "post_processing"):
if not isinstance(request.post_processing, PostProcessingTask):
raise ValueError()
response.call_on_close(request.post_processing.execute)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment