Skip to content

Instantly share code, notes, and snippets.

@robertklep
Created June 13, 2012 19:49
Show Gist options
  • Save robertklep/2926053 to your computer and use it in GitHub Desktop.
Save robertklep/2926053 to your computer and use it in GitHub Desktop.
Wrapper function for Django middleware classes so they handle text/event-stream
# wrapper for middleware classes (I'm using this in combination with django-sse)
def EventStreamMiddlewareWrapper(original):
original_method = getattr(original, 'process_response', None)
if not original_method:
return original
def new_method(self, request, response):
# return immediately when the response is an event stream
if 'text/event-stream' in response.get('Content-Type', ''):
return response
# otherwise, pass to original method
return original_method(self, request, response)
# monkeypatch original process_response method
original.process_response = new_method
return original
# example:
#
# - mymiddleware.py -
# import django.middleware.http
# ConditionalGetMiddleware = EventStreamMiddlewareWrapper(django.middleware.http.ConditionalGetMiddleware)
#
# - settings.py -
# MIDDLEWARE_CLASSES = (
# ...
# 'mymiddleware.ConditionalGetMiddleware',
# ...
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment