1

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.

Community
  • 1
  • 1
Aryeh Leib Taurog
  • 5,370
  • 1
  • 42
  • 49

1 Answers1

3

The Session Middleware is used by Message Middleware. We usually like to exclude Message Middleware from Transactions.

From Messages Middleware page

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.

Pratyush
  • 5,108
  • 6
  • 41
  • 63
  • Using session to convey messages about transaction failure is a great use case. Thank you. Can you explain what you mean by long running processes? You mean log running requests, like a large-file upload? – Aryeh Leib Taurog Mar 13 '12 at 19:45
  • Yup, long running requests/processes is like large-file upload or even cases where process takes time on server side. Say your are saving all tweets of a user in database using API. You might like to keep updating the status of the job by saving status in session and retrieving it using AJAX. – Pratyush Mar 13 '12 at 19:52