Skip to content

Instantly share code, notes, and snippets.

@flyakite
Last active August 29, 2015 13:56
Show Gist options
  • Save flyakite/8817744 to your computer and use it in GitHub Desktop.
Save flyakite/8817744 to your computer and use it in GitHub Desktop.
Some requests require no session, auth, locale, csrf check, message, or many other middlewares. Especially, there are some useless db connection in django_session. Skip unnecessary middlewares can make the request much faster.
#
# in your settings file
#
# middleware settings
MIDDLEWARE_CLASSES = (
'some.essential.Middleware',
# this is the home-made shortcut middleware, put right above the middlewares you want to skip
'apps.middleware.ShortcutMiddleware',
# some middlewares you want to skip
'django.contrib.sessions.middleware.SessionMiddleware',
...
)
# paths you want to apply the shortcut
SHORTCUT_MIDDLEWARE_PATHS = [
'/heavy_request_path_supposed_to_be_fast/',
]
#
# create you own middleware.py
#
from django.conf import settings
class ShortcutMiddleware(object):
"""
doc: https://docs.djangoproject.com/en/dev/topics/http/middleware/
"""
def process_view(self, request, view_func, view_args, view_kwargs):
"""
process_view will be called just before django called view
"""
if request.path in settings.SHORTCUT_MIDDLEWARE_PATHS:
return view_func(request, *view_args, **view_kwargs)
return None # if preoces_view returns None, continue to process other middlewares
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment