[Answer]-Django bootstrap/middleware/enter-exit



  1. In your middleware, you can create new object for data you want to maintain and put it in request.META dict. It will be available wherever, request is available. In this case, I don’t think you need to worry about thread-safety as each request will create new object.

  2. If you want to just create data object once when request processing starts, destroy after processing the request and no other code references this data then you can look at request_started and request_finished signals.



Middleware is very certainly not thread-safe. You should not store anything per-request either on the middleware object, or in the global namespace.

The usual way to do this is sort of thing to annotate it onto the request object. Middleware and views have access to this, but to get it anywhere else (eg in the model) you’ll need to pass it around.

Leave a comment