Session middleware: before or after transaction middleware?
-
12-12-2019 - |
Question
Regarding the order of middleware, this question states:
SessionMiddleware
- Before
TransactionMiddleware
: we don't need transactions here
Why would I not want my session updates in my transaction? If the session is updated as a side effect of something which occurs in the view and the view fails, I cannot imagine a case where I would want the session to be nonetheless updated as if it had not failed. (Clearly if the session engine is not db-based, this problem would have to be approached some other way.)
Please provide a clear use case why I might want the SessionMiddleware
to run outside the TransactionMiddleware
.
Solution
The Session Middleware is used by Message Middleware. We usually like to exclude Message Middleware from Transactions.
If you are using a storage backend that relies on sessions (the default), 'django.contrib.sessions.middleware.SessionMiddleware' must be enabled and appear before MessageMiddleware in your MIDDLEWARE_CLASSES.
Since we might want to show up transaction failures as user messages, thus we exclude Message Middle-ware from Transactions.
Also in long running processes, I usually use Messages/Session to keep updating the process status. The same is retrieved by an Ajax call. If Message or Session MW is placed after Transactions, then the status updates won't respond.