[Web-SIG] Alternative to threading.local, based on the stack
Robert Brewer
fumanchu at aminus.org
Fri Jul 4 19:52:56 CEST 2008
Benji York wrote:
> On Fri, Jul 4, 2008 at 9:23 AM, Iwan Vosloo <iwan at reahl.org> wrote:
> > On Fri, 2008-07-04 at 13:39 +0100, Matt Goodall wrote:
> >> The ideal solution is, of course, to pass everything around to
> whatever
> >> needs it. However, there's really tedious at times.
> >>
> >> Whatever the architecture of the web server there is always a
> request
> >> or, in case of WSGI, an env dict. Therefore, request-scope objects
> >> should be associated with the request.
> >
> > True, but even passing a request or env dict around to everyone gets
> > tedious don't you think?
>
> It can. Zope 3 makes a pretty good compromise here. The "top level"
> object involved in handing the request -- a view -- gets the request
> object explicitly passed as a parameter. If the view wants to pass
the
> request to function calls or other objects, then it's free to do so.
>
> But, if at some point you find yourself without a reference to the
> current request and really need it, you can get it "out of thin air"
by
> calling (essentially) get_request().
>
> The Zope 3 publisher precesses requests using a thread pool, so
> get_request() is implemented by stashing the request object in the
> tread-local storage prior to processing the request and digging it
back
> out if requested.
>
> Other implementations could store the request somewhere else, but the
> idea is the same.
CherryPy does something similar. The "top level" object involved in
handing the request -- cherrypy.serving -- gets the request and response
objects set as attributes. But instead of calling get_request() as in
Zope 3, there are proxy objects sitting at cherrypy.request and
cherrypy.response which shuttle getattr and setattr to
cherrypy.serving.request/response. That allows app code to just "import
cherrypy" and have access everywhere.
Now, cherrypy.serving _is_ a threadlocal object. But I don't imagine it
would be difficult for a non-threaded HTTP server to replace
cherrypy.serving with some other-context-local if they liked.
Robert Brewer
fumanchu at aminus.org
More information about the Web-SIG
mailing list