[Web-SIG] Using decorators to add objects in a thread-local store..
robillard.etienne at gmail.com
Wed Jul 16 18:55:41 CEST 2008
On Tue, 15 Jul 2008 21:32:39 -0500
Ian Bicking <ianb at colorstudy.com> wrote:
> Etienne Robillard wrote:
> > Hi all,
> > I'd like to have your input and comments on using decorators
> > functions for adding extra options to the request.environ object.
> > For instance, here's a decorator whichs adds a "scoped" session
> > object into request.environ:
> > def with_session(engine=None):
> > """
> > Decorator function for attaching a `Session` instance
> > as a keyword argument in `request.environ`.
> > """
> > def decorator(view_func):
> > def _wrapper(request, *args, **kwargs):
> > scoped_session.set_session(engine)
> > request.environ['_scoped_session'] = getattr(scoped_session, 'sessio
> You should always use a namespace, e.g.,
> request.environ['something._scoped_session'] = ...
> In the context of a Pylons controller you could do it this way. Of
> course with just WSGI it would be better to wrap it via WSGI, which is
> almost equivalent to a decorator:
> def with_session(engine=None):
> def decorator(app):
> def engine_wsgi_app(environ, start_response):
> environ['...'] = ...
> return app(environ, start_response)
> return engine_wsgi_app
> return decorator
Tried, but its giving me headaches.. I think I will stick with the
former... Plus, in webob, it is my assumption that Request objects
returns a wsgi application with get_response(). This indicates most
likely that both approaches are the same. :)
> Pylons controllers aren't *quite* WSGI applications, but instances of
> those controller classes are. So wrapping an individual controller with
> middleware requires a bit more work.
Ah. I just have a conflicting view regarding the definition of a 'middleware'.
For me, middlewares shouldn't even exists, as I'm not even sure where they should
fit in the WSGI pipeline.. In fact, I consider middlewares as a potential security hole...
> > @with_session(engine=engine):
> > def view_blog_list(request, *args, **kwargs):
> > # get the local session object for this
> > # request (thread-local)
> > sess = request.environ['_scoped_session']
> > # do stuff with the Session object here...
> > ...
> > Is this a good approach, or can this be adapted to work
> > in multithreaded environments ?
> Since you are passing around arguments to functions it should be fine in
> threaded environments.
Thanks. I'd definitely like to see more discussion regarding threads in the
next version of WSGI.
> Ian Bicking : ianb at colorstudy.com : http://blog.ianbicking.org
More information about the Web-SIG