Better handling of function arguments as params (POST or GET)

This commit is contained in:
Christophe de Vienne 2011-11-28 18:32:51 +01:00
parent d24ea244a6
commit 3e49c50db6
2 changed files with 86 additions and 4 deletions

76
wsme/protocols/commons.py Normal file
View File

@ -0,0 +1,76 @@
import datetime
import re
from simplegeneric import generic
from wsme.types import iscomplex, list_attributes, Unset
from wsme.utils import parse_isodate, parse_isotime, parse_isodatetime
ARRAY_MAX_SIZE = 1000
@generic
def from_param(datatype, value):
return datatype(value) if value else None
@from_param.when_object(datetime.date)
def date_from_param(datatype, value):
return parse_isodate(value) if value else None
@from_param.when_object(datetime.time)
def time_from_param(datatype, value):
return parse_isotime(value) if value else None
@from_param.when_object(datetime.datetime)
def datetime_from_param(datatype, value):
return parse_isodatetime(value) if value else None
@generic
def from_params(datatype, params, path):
if iscomplex(datatype):
objfound = False
for key in params:
if key.startswith(path + '.'):
objfound = True
break
if objfound:
r = datatype()
for attrdef in list_attributes(datatype):
value = from_params(attrdef.datatype,
params, '%s.%s' % (path, attrdef.key))
if value is not Unset:
setattr(r, attrdef.key, value)
return r
else:
if path in params:
return from_param(datatype, params[path])
return Unset
@from_params.when_type(list)
def array_from_params(datatype, params, path):
if path in params:
return [
from_param(datatype[0], value) for value in params.getall(path)]
else:
indexes = set()
r = re.compile('^%s\[(?P<index>\d+)\]' % path)
for p in params.keys():
m = r.match(p)
if m:
indexes.add(int(m.group('index')))
if not indexes:
return Unset
indexes = list(indexes)
indexes.sort()
return [from_params(datatype[0], params, '%s[%s]' % (path, index))
for index in indexes]

View File

@ -1,7 +1,9 @@
import logging
from wsme.exc import UnknownFunction, MissingArgument, UnknownArgument
from wsme.exc import ClientSideError, UnknownArgument
from wsme.protocols import CallContext
from wsme.protocols.commons import from_params
from wsme.types import Unset
log = logging.getLogger(__name__)
@ -42,9 +44,13 @@ class RestProtocol(object):
body = request.params['body']
if body is None and len(request.params):
parsed_args = {}
for key, value in request.params.items():
parsed_args[key] = self.parse_arg(key, value)
kw = {}
for argdef in funcdef.arguments:
value = from_params(
argdef.datatype, request.params, argdef.name)
if value is not Unset:
kw[argdef.name] = value
return kw
else:
if body is None:
body = request.body