Table Of Contents

Context Locals

Werkzeug is the Swiss Army knife of Python web development.

It provides useful classes and functions for any WSGI application to make the life of a python web developer much easier. All of the provided classes are independed from each other so you can mix it with any other library.


class werkzeug.LocalManager(locals=None)

Local objects cannot manage themselves. For that you need a local manager. You can pass a local manager multiple locals or add them later by appending them to manager.locals. Everytime the manager cleans up it, will clean up all the data left in the locals for this context.

Manually clean up the data in the locals for this context. Call this at the end of the request or use make_middleware().
Wrap a WSGI application so that cleaning up happens after request end.

Like make_middleware but for decorating functions.

Example usage:

def application(environ, start_response):

The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module).

Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy’s scoped sessions) to the Werkzeug locals.
class werkzeug.LocalProxy(local, name)

Acts as a proxy for a werkzeug local. Forwards all operations to a proxied object. The only operations not supported for forwarding are right handed operands and any kind of assignment.

Example usage:

from werkzeug import Local
l = Local()
request = l('request')
user = l('user')

Whenever something is bound to l.user / l.request the proxy objects will forward all operations. If no object is bound a RuntimeError will be raised.

Keep in mind that repr() is also forwarded, so if you want to find out if you are dealing with a proxy you can do an isinstance() check:

>>> from werkzeug import LocalProxy
>>> isinstance(request, LocalProxy)

You can also create proxy objects by hand:

from werkzeug import Local, LocalProxy
local = Local()
request = LocalProxy(local, 'request')
Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.