Skip to content

Commit

Permalink
Merge 1b145ec into 1fe65dd
Browse files Browse the repository at this point in the history
  • Loading branch information
arajkumar committed Mar 12, 2020
2 parents 1fe65dd + 1b145ec commit 6da8cba
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions flask_restplus/fields.py
Expand Up @@ -42,6 +42,10 @@ def is_indexable_but_not_string(obj):
return not hasattr(obj, "strip") and hasattr(obj, "__iter__")


def is_integer_indexable(obj):
return isinstance(obj, list) or isinstance(obj, tuple)


def get_value(key, obj, default=None):
'''Helper for pulling a keyed value off various types of objects'''
if isinstance(key, int):
Expand All @@ -66,6 +70,11 @@ def _get_value_for_key(key, obj, default):
return obj[key]
except (IndexError, TypeError, KeyError):
pass
if is_integer_indexable(obj):
try:
return obj[int(key)]
except (IndexError, TypeError, ValueError):
pass
return getattr(obj, key, default)


Expand Down
12 changes: 12 additions & 0 deletions tests/test_fields.py
Expand Up @@ -1379,3 +1379,15 @@ def __getitem__(self, n):

obj = Test('hi')
assert fields.get_value('value', obj) == 'hi'

def test_get_value_int_indexable_list(self):
assert fields.get_value('bar.0', {'bar': [42]}) == 42

def test_get_value_int_indexable_nested_list(self):
assert fields.get_value('bar.0.val', {'bar': [{'val': 42}]}) == 42

def test_get_value_int_indexable_tuple(self):
assert fields.get_value('bar.0', {'bar': (42, 43)}) == 42

def test_get_value_int_indexable_nested_tuple(self):
assert fields.get_value('bar.0.val', {'bar': [{'val': 42}]}) == 42

0 comments on commit 6da8cba

Please sign in to comment.