[Web-SIG] Alternative to threading.local, based on the stack

Iwan Vosloo iwan at reahl.org
Fri Jul 4 13:13:57 CEST 2008


Hi,

Many web frameworks and ORM tools have the need to propagate data
depending on some or other context within which a request is dealt with.
Passing it all via parameters to every nook of your code is cumbersome.

A lot of the frameworks use a thread local context to solve this
problem. I'm assuming these are based on threading.local.  

(See, for example:
http://www.sqlalchemy.org/docs/05/session.html#unitofwork_contextual )

Such usage assumes that one request is served per thread.

This is not necessarily the case.  (Twisted would perhaps be an example,
but I have not checked how the twisted people deal with the issue.)

The bottom line for me is that if you build a WSGI app, you'd not want
to restrict it to being able to run in a one request-per-thread setup.

So I've been playing with the idea to use something that creates a
context local to the current call stack instead. I.e. a context (dict)
which is inserted into the call stack at some point, and can be accessed
by any method/function deeper in the stack.

The normal use case for this is to propagate a database connection. But
it can also be used to propagate other things, such as information about
the user who is currently logged in, etc.

Since this is one way of creating objects that are global to a context
(the call stack), I'm sure it is in some ways evil and can be abused.
But that criticism can be levelled against the thread-local solution
too...

I attach some code to illustrate - and would appreciate some feedback on
the idea and its implementation.

-i
-------------- next part --------------
A non-text attachment was scrubbed...
Name: callcontext.py
Type: text/x-python
Size: 3397 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/web-sig/attachments/20080704/8c97af36/attachment.py>


More information about the Web-SIG mailing list