mod_wsgi + threading.local: Is it safe?

91 views
Skip to first unread message

Frederik Vogelsang

unread,
Apr 27, 2012, 3:40:09 PM4/27/12
to mod...@googlegroups.com
Hello everyone.

I am working on a Django application which is served through Apache
and mod_wsgi.
We need access to the user object in models (without Django's usual
request.user context). I am planning to use threading.local() for
this. Is there anything to look out for when doing this? Is this even
save? It would be a severe issue if a request's thread-local data
could be destroyed/overwritten by another (maybe parallel) request,
this is why I am asking.


Kind regards,
Frederik

Jason Garber

unread,
Apr 27, 2012, 4:03:45 PM4/27/12
to mod...@googlegroups.com
I have used threading.local as a base class for years in heavy production use with no problem.  We use it for database connections, etc...  mod_wsgi will never try to send two requests to the same thread at the same time, so it is quite safe.

Keep in mind that if you derive a class from threading.local, the __init__ method will be called once per thread.  Just FYI.

Hope this helps.
JG


--
You received this message because you are subscribed to the Google Groups "modwsgi" group.
To post to this group, send email to mod...@googlegroups.com.
To unsubscribe from this group, send email to modwsgi+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/modwsgi?hl=en.


Frederik Vogelsang

unread,
Apr 28, 2012, 11:43:05 AM4/28/12
to mod...@googlegroups.com
Hi,

thanks a lot for the input. It's good to know that this is working out
for you. I also found this statement in the mod_wsgi docs under
"Building A Portable Application":
"Data which needs to exist for the life of the request, would need to
be stored as stack based data, *thread local data*, or cached in the
WSGI application environment."

I guess I'll just use threading.local then to store the request's
authentication information globally.


Regards,
Frederik

2012/4/27 Jason Garber <ja...@gahooa.com>:

Jason Garber

unread,
Apr 28, 2012, 5:56:48 PM4/28/12
to mod...@googlegroups.com

I still use postgres for session data, but suggest you check out redis.io as a way of having true global data even with load balancing or multiple processes.

Reply all
Reply to author
Forward
0 new messages