1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
|
"""
Decorators to wrap functions to make them WSGI applications.
The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
"""
import webob
import webob.exc
from types import ClassType
__all__ = ['wsgify']
class wsgify(object):
"""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 :mod:`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 :class:`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 :class:`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 :mod:`webob.exc`
Also see :func:`wsgify.middleware` for a way to make middleware.
You can also subclass this decorator; the most useful things to do
in a subclass would be to change `RequestClass` or override
`call_func` (e.g., to add ``req.urlvars`` as keyword arguments to
the function).
"""
RequestClass = webob.Request
def __init__(self, func=None, RequestClass=None,
args=(), kwargs=None, middleware_wraps=None):
self.func = func
if (RequestClass is not None
and RequestClass is not self.RequestClass):
self.RequestClass = RequestClass
self.args = tuple(args)
if kwargs is None:
kwargs = {}
self.kwargs = kwargs
self.middleware_wraps = middleware_wraps
def __repr__(self):
if self.func is None:
args = []
else:
args = [_func_name(self.func)]
if self.RequestClass is not self.__class__.RequestClass:
args.append('RequestClass=%r' % self.RequestClass)
if self.args:
args.append('args=%r' % (self.args,))
my_name = self.__class__.__name__
if self.middleware_wraps is not None:
my_name = '%s.middleware' % my_name
else:
if self.kwargs:
args.append('kwargs=%r' % self.kwargs)
r = '%s(%s)' % (my_name, ', '.join(args))
if self.middleware_wraps is not None:
args = [repr(self.middleware_wraps)]
if self.kwargs:
args.extend(['%s=%r' % (name, value)
for name, value in sorted(self.kwargs.items())])
r += '(%s)' % ', '.join(args)
return r
def __get__(self, obj, type=None):
# This handles wrapping methods
if hasattr(self.func, '__get__'):
return self.clone(self.func.__get__(obj, type))
else:
return self
def __call__(self, req, *args, **kw):
"""Call this as a WSGI application or with a request"""
func = self.func
if func is None:
if args or kw:
raise TypeError(
"Unbound %s can only be called with the function it will wrap"
% self.__class__.__name__)
func = req
return self.clone(func)
if isinstance(req, dict):
if len(args) != 1 or kw:
raise TypeError(
"Calling %r as a WSGI app with the wrong signature")
environ = req
start_response = args[0]
req = self.RequestClass(environ)
req.response = req.ResponseClass()
req.response.request = req
try:
args = self.args
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
resp = self.call_func(req, *args, **self.kwargs)
except webob.exc.HTTPException, resp:
pass
if resp is None:
## FIXME: I'm not sure what this should be?
resp = req.response
elif isinstance(resp, basestring):
body = resp
resp = req.response
resp.write(body)
if resp is not req.response:
resp = req.response.merge_cookies(resp)
return resp(environ, start_response)
else:
return self.func(req, *args, **kw)
def get(self, url, **kw):
"""Run a GET request on this application, returning a Response.
This creates a request object using the given URL, and any
other keyword arguments are set on the request object (e.g.,
``last_modified=datetime.now()``).
::
resp = myapp.get('/article?id=10')
"""
kw.setdefault('method', 'GET')
req = self.RequestClass.blank(url, **kw)
return self(req)
def post(self, url, POST=None, **kw):
"""Run a POST request on this application, returning a Response.
The second argument (`POST`) can be the request body (a
string), or a dictionary or list of two-tuples, that give the
POST body.
::
resp = myapp.post('/article/new',
dict(title='My Day',
content='I ate a sandwich'))
"""
kw.setdefault('method', 'POST')
req = self.RequestClass.blank(url, POST=POST, **kw)
return self(req)
def request(self, url, **kw):
"""Run a request on this application, returning a Response.
This can be used for DELETE, PUT, etc requests. E.g.::
resp = myapp.request('/article/1', method='PUT', body='New article')
"""
req = self.RequestClass.blank(url, **kw)
return self(req)
def call_func(self, req, *args, **kwargs):
"""Call the wrapped function; override this in a subclass to
change how the function is called."""
return self.func(req, *args, **kwargs)
def clone(self, func=None, **kw):
"""Creates a copy/clone of this object, but with some
parameters rebound
"""
kwargs = {}
if func is not None:
kwargs['func'] = func
if self.RequestClass is not self.__class__.RequestClass:
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)
return self.__class__(**kwargs)
# To match @decorator:
@property
def undecorated(self):
return self.func
@classmethod
def middleware(cls, middle_func=None, app=None, **kw):
"""Creates middleware
Use this like::
@wsgify.middleware
def restrict_ip(app, req, ips):
if req.remote_addr not in ips:
raise webob.exc.HTTPForbidden('Bad IP: %s' % req.remote_addr)
return app
@wsgify
def app(req):
return 'hi'
wrapped = restrict_ip(app, ips=['127.0.0.1'])
Or if you want to write output-rewriting middleware::
@wsgify.middleware
def all_caps(app, req):
resp = req.get_response(app)
resp.body = resp.body.upper()
return resp
wrapped = all_caps(app)
Note that you must call ``req.get_response(app)`` to get a WebOb response
object. If you are not modifying the output, you can just return the app.
As you can see, this method doesn't actually create an application, but
creates "middleware" that can be bound to an application, along with
"configuration" (that is, any other keyword arguments you pass when
binding the application).
"""
if middle_func is None:
return _UnboundMiddleware(cls, app, kw)
if app is None:
return _MiddlewareFactory(cls, middle_func, kw)
return cls(middle_func, middleware_wraps=app, kwargs=kw)
class _UnboundMiddleware(object):
"""A `wsgify.middleware` invocation that has not yet wrapped a
middleware function; the intermediate object when you do
something like ``@wsgify.middleware(RequestClass=Foo)``
"""
def __init__(self, wrapper_class, app, kw):
self.wrapper_class = wrapper_class
self.app = app
self.kw = kw
def __repr__(self):
if self.app:
args = (self.app,)
else:
args = ()
return '%s.middleware(%s)' % (
self.wrapper_class.__name__,
_format_args(args, self.kw))
def __call__(self, func, app=None):
if app is None:
app = self.app
return self.wrapper_class.middleware(func, app=app, **self.kw)
class _MiddlewareFactory(object):
"""A middleware that has not yet been bound to an application or
configured.
"""
def __init__(self, wrapper_class, middleware, kw):
self.wrapper_class = wrapper_class
self.middleware = middleware
self.kw = kw
def __repr__(self):
return '%s.middleware(%s)' % (
self.wrapper_class.__name__,
_format_args((self.middleware,), self.kw))
def __call__(self, app, **config):
kw = self.kw.copy()
kw.update(config)
return self.wrapper_class.middleware(self.middleware, app, **kw)
def _func_name(func):
"""Returns the string name of a function, or method, as best it can"""
if isinstance(func, (type, ClassType)):
name = func.__name__
if func.__module__ not in ('__main__', '__builtin__'):
name = '%s.%s' % (func.__module__, name)
return name
name = getattr(func, 'func_name', None)
if name is None:
name = repr(func)
else:
name_self = getattr(func, 'im_self', None)
if name_self is not None:
name = '%r.%s' % (name_self, name)
else:
name_class = getattr(func, 'im_class', None)
if name_class is not None:
name = '%s.%s' % (name_class.__name__, name)
module = getattr(func, 'func_globals', {}).get('__name__')
if module and module != '__main__':
name = '%s.%s' % (module, name)
return name
def _format_args(args=(), kw=None, leading_comma=False, obj=None, names=None, defaults=None):
if kw is None:
kw = {}
all = [repr(arg) for arg in args]
if names is not None:
assert obj is not None
kw = {}
if isinstance(names, basestring):
names = names.split()
for name in names:
kw[name] = getattr(obj, name)
if defaults is not None:
kw = kw.copy()
for name, value in defaults.items():
if name in kw and value == kw[name]:
del kw[name]
all.extend(['%s=%r' % (name, value) for name, value in sorted(kw.items())])
result = ', '.join(all)
if result and leading_comma:
result = ', ' + result
return result
|