Skip to content

Commit

Permalink
Add support for complex query args
Browse files Browse the repository at this point in the history
  • Loading branch information
apiad committed Jan 23, 2018
1 parent 6861806 commit 9235515
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 12 deletions.
17 changes: 17 additions & 0 deletions docs/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,20 @@ Default arguments are, of course, default:
{'mult': 42}

```

## Complex query args

If your function receives a complex argument (i.e., a JSON dict), you will automatically receive a parsed `JsonObj` that you can manipulate with dot-notation access for attributes:

```python
>>> class ComplexArg(JsonApi):
... def process(self, x):
... return x.message.format(x.name)

>>> api = ComplexArg()
>>> api({ 'process': { '$x': { 'name': 'world', 'message': 'Hello {0}!'} }})
{'process': 'Hello world!'}

```

You can read more about `JsonObj`'s magic tricks [here](/jsonobj.md).
42 changes: 30 additions & 12 deletions jsonapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@


class JsonObj:
def __init__(self, **kwargs):
for k,w in kwargs.items():
setattr(self, str(k), self._parse(w))

def _json(self, x, query):
if isinstance(x, (int, float, str)):
if x is None:
return None
if isinstance(x, (int, float, str, bool)):
return x
if isinstance(x, (list, tuple)):
return [self._json(i, query) for i in x]
Expand All @@ -15,36 +21,48 @@ def _json(self, x, query):
return x._query(query)
raise TypeError("type %s is not supported" % type(x))

def _parse(self, x):
if x is None:
return None
if isinstance(x, (int, float, str, bool)):
return x
if isinstance(x, list):
return [self._parse(i) for i in x]
if isinstance(x, dict):
return JsonObj(**x)
raise TypeError("type %s is not supported" % type(x))

def _query(self, query):
if query is None:
return {k: v for k, v in self.__dict__.items() if not hasattr(v, '__call__')}
return {key: value for key, value in self.__dict__.items() if not hasattr(value, '__call__')}

payload = {}

if isinstance(query, dict):
items = query.items()
else:
items = [(k, None) for k in query]
items = [(key, None) for key in query]

for k,v in items:
attr = getattr(self, k)
for key, value in items:
attr = getattr(self, key)
args = {}
navigation = v
navigation = value

if isinstance(v, dict):
if "$" in v:
args = v.pop("$")
if isinstance(navigation, dict):
if "$" in navigation:
args = { str(k): self._parse(v) for k,v in navigation.pop("$").items() }
else:
for a in list(v.keys()):
for a in list(navigation.keys()):
if a.startswith("$"):
args[a.strip("$")] = v.pop(a)
v = navigation.pop(a)
args[a.strip("$")] = self._parse(v)

if hasattr(attr, '__call__'):
result = attr(**args)
else:
result = attr

payload[k] = self._json(result, navigation)
payload[key] = self._json(result, navigation)

return payload

Expand Down

0 comments on commit 9235515

Please sign in to comment.