3

Recently I've started using threading.local() as way for some apis to store and access state for duration of request without having to access request object.

So lets say I have certain code:

_thread_local = threading.local()
_thread_local.theme = 'darkblues'

How long does that _thread_local.theme variable lasts? Do I have to manually unset it at the end of request in, say, custom middleware? Or it's deleted by Django automatically after it finishes processing request?

Ralfp
  • 480
  • 5
  • 10

1 Answers1

1

It will last as long as threading.local() lasts, which is the lifetime of the request. Nothing special is required after that. Django doesn't do much to manage state on thread locals, so things might stick around after the request is over. Is this really a problem? You would probably end up setting the value to whatever it needs to be in the next request.

davidism
  • 121,510
  • 29
  • 395
  • 339