webob.dec – WSGIfy decorator
Decorators to wrap functions to make them WSGI applications.
The main decorator wsgify turns a function into a WSGI application (while also allowing normal calling of the method with an instantiated request).
Decorator
class webob.dec.wsgify(func=None, RequestClass=None, args=(), kwargs=None, middleware_wraps=None)
Turns a request-taking, response-returning function into a WSGI app
You can use this like:
@wsgify
def myfunc(req):
return webob.Response('hey there')
With that myfunc will be a WSGI application, callable like app_iter = myfunc(environ, start_response). You can also call it like normal, e.g., resp = myfunc(req). (You can also wrap methods, like def myfunc(self, req).)
If you raise exceptions from webob.exc they will be turned into WSGI responses.
There are also several parameters you can use to customize the decorator. Most notably, you can use a webob.Request subclass, like:
class MyRequest(webob.Request):
@property
def is_local(self):
return self.remote_addr == '127.0.0.1'
@wsgify(RequestClass=MyRequest)
def myfunc(req):
if req.is_local:
return Response('hi!')
else:
raise webob.exc.HTTPForbidden
Another customization you can add is to add args (positional arguments) or kwargs (of course, keyword arguments). While generally not that useful, you can use this to create multiple WSGI apps from one function, like:
import simplejson
def serve_json(req, json_obj):
return Response(json.dumps(json_obj),
content_type='application/json')
serve_ob1 = wsgify(serve_json, args=(ob1,))
serve_ob2 = wsgify(serve_json, args=(ob2,))
You can return several things from a function:
A webob.Response object (or subclass)
Any WSGI application
None, and then req.response will be used (a pre-instantiated Response object)
A string, which will be written to req.response and then that response will be used.
Raise an exception from webob.exc