Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Unable to access nested list property #784

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions flask_restplus/fields.py
Original file line number Diff line number Diff line change
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
18 changes: 18 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1379,3 +1379,21 @@ 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_list_with_str(self):
assert fields.get_value('bar.abc', {'bar': [42]}) == None

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_with_str(self):
assert fields.get_value('bar.abc', {'bar': (42, 43)}) == None

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