Practiaal rules for Django MiddleWare ordering?

Posted by o_O Tync on Stack Overflow See other posts from Stack Overflow or by o_O Tync
Published on 2011-01-08T04:26:17Z Indexed on 2011/01/08 21:53 UTC
Read the original article Hit count: 299

Filed under:
|

The official documentation is a bit messy: 'before' & 'after' are used for ordering MiddleWare in a tuple, but in some places 'before'&'after' refers to request-response phases. Also, 'should be first/last' are mixed and it's not clear which one to use as 'first'.

I do understand the difference.. however it seems to complicated for a newbie in Django.

Can you suggest some correct ordering for builtin MiddleWare classes (assuming we enable all of them) and — most importantly — explain WHY one goes before/after other ones?

here's the list, with the info from docs I managed to find:

  1. UpdateCacheMiddleware
    • Before those that modify 'Vary:' SessionMiddleware, GZipMiddleware, LocaleMiddleware
  2. GZipMiddleware
    • Before any MW that may change or use the response body
    • After UpdateCacheMiddleware: Modifies 'Vary:'
  3. ConditionalGetMiddleware
    • Before CommonMiddleware: uses its 'Etag:' header when USE_ETAGS=True
  4. SessionMiddleware
    • After UpdateCacheMiddleware: Modifies 'Vary:'
    • Before TransactionMiddleware: we don't need transactions here
  5. LocaleMiddleware, One of the topmost, after SessionMiddleware, CacheMiddleware
    • After UpdateCacheMiddleware: Modifies 'Vary:'
    • After SessionMiddleware: uses session data
  6. CommonMiddleware
    • Before any MW that may change the response (it calculates ETags)
    • After GZipMiddleware so it won't calculate an E-Tag on gzipped contents
    • Close to the top: it redirects when APPEND_SLASH or PREPEND_WWW
  7. CsrfViewMiddleware
  8. AuthenticationMiddleware
    • After SessionMiddleware: uses session storage
  9. MessageMiddleware
    • After SessionMiddleware: can use Session-based storage
  10. XViewMiddleware
  11. TransactionMiddleware
    • After MWs that use DB: SessionMiddleware (configurable to use DB)
    • All *CacheMiddleWare is not affected (as an exception: uses own DB cursor)
  12. FetchFromCacheMiddleware
    • After those those that modify 'Vary:' if uses them to pick a value for cache hash-key
    • After AuthenticationMiddleware so it's possible to use CACHE_MIDDLEWARE_ANONYMOUS_ONLY
  13. FlatpageFallbackMiddleware
    • Bottom: last resort
    • Uses DB, however, is not a problem for TransactionMiddleware (yes?)
  14. RedirectFallbackMiddleware
    • Bottom: last resort
    • Uses DB, however, is not a problem for TransactionMiddleware (yes?)

(I will add suggestions to this list to collect all of them in one place)

© Stack Overflow or respective owner

Related posts about django

Related posts about django-middleware