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 #93

Merged
merged 14 commits into from
Jan 11, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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_restx/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,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 @@ -91,6 +95,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 @@ -1369,3 +1369,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
arajkumar marked this conversation as resolved.
Show resolved Hide resolved

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
arajkumar marked this conversation as resolved.
Show resolved Hide resolved

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