Skip to content

Instantly share code, notes, and snippets.

@pirate
Last active June 24, 2019 03:08
Show Gist options
  • Save pirate/c4deb41c16793c05950a6721a820cde9 to your computer and use it in GitHub Desktop.
Save pirate/c4deb41c16793c05950a6721a820cde9 to your computer and use it in GitHub Desktop.
"""Run some code after the response is returned to the user in django
Great for analytics or other slow tasks that you don't want to block the response
to the user for.
"""
class HttpResponseWithCallback(HttpResponse):
def __init__(self, *args, **kwargs):
self.callback = kwargs.pop('callback')
super().__init__(*args, **kwargs)
def close(self):
super().close()
self.callback(response=self)
def my_view(request):
...
return HttpResponseWithCallback(..., callback=some_expensive_function)
# can also easily be put on a class-based view as a View.after_response method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment