[Tutor] threading.currentThread() always same across request ?

Kent Johnson kent37 at tds.net
Sat Apr 14 13:26:41 CEST 2007

Arun Kumar PG wrote:
> Guys,
> I have a web application and I want to store an object per request so 
> thta that is available across all classes till end of request.
> I am planning  to write the below code in my entry program which is 
> executed as soon as a request comes:
> entry.py
>   import threading
>   th = threading.currentThread()
>   th.service = somemod.Service()
> then in other parts of program whereever I want to use service:
>   th = threading.currentThread ()
>   if hasattr(th, 'service'):
>     th.service.call_whatever()

Rather than store your attributes directly in the thread, it would 
probably be better to use a threading.local() object as the container.

I don't really know if it makes any difference but this is the supported 
mechanism for thread-local storage.

> I am wondering if I will ever face a problem in this case ? I want to 
> make sure that since the request till the end the same "service" object 
> is available and it should not collide with any other request. Since 
> it's a web application multilple request may come simutaneously.

You have to be careful that you don't get stale data, as threads are 
often reused in web servers. At the end of the request processing you 
should clear out your local data.

If you are using an existing web framework it probably has some kind of 
support for sessions. Using session objects might be another way to do this.


More information about the Tutor mailing list