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
|
import inspect
import wsme.api
APIPATH_MAXLEN = 20
class expose(object):
def __init__(self, *args, **kwargs):
self.signature = wsme.api.signature(*args, **kwargs)
def __call__(self, func):
return self.signature(func)
@classmethod
def with_method(cls, method, *args, **kwargs):
kwargs['method'] = method
return cls(*args, **kwargs)
@classmethod
def get(cls, *args, **kwargs):
return cls.with_method('GET', *args, **kwargs)
@classmethod
def post(cls, *args, **kwargs):
return cls.with_method('POST', *args, **kwargs)
@classmethod
def put(cls, *args, **kwargs):
return cls.with_method('PUT', *args, **kwargs)
@classmethod
def delete(cls, *args, **kwargs):
return cls.with_method('DELETE', *args, **kwargs)
class validate(object):
"""
Decorator that define the arguments types of a function.
Example::
class MyController(object):
@expose(str)
@validate(datetime.date, datetime.time)
def format(self, d, t):
return d.isoformat() + ' ' + t.isoformat()
"""
def __init__(self, *param_types):
self.param_types = param_types
def __call__(self, func):
argspec = wsme.api.getargspec(func)
fd = wsme.api.FunctionDefinition.get(func)
fd.set_arg_types(argspec, self.param_types)
return func
def scan_api(controller, path=[], objects=[]):
"""
Recursively iterate a controller api entries.
"""
for name in dir(controller):
if name.startswith('_'):
continue
a = getattr(controller, name)
if a in objects:
continue
if inspect.ismethod(a):
if wsme.api.iswsmefunction(a):
yield path + [name], a, []
elif inspect.isclass(a):
continue
else:
if len(path) > APIPATH_MAXLEN:
raise ValueError("Path is too long: " + str(path))
for i in scan_api(a, path + [name], objects + [a]):
yield i
|