Skip to content

Commit

Permalink
Set kwargs_to_list to force str/unicode to str when nested in a dic…
Browse files Browse the repository at this point in the history
…t or list.

Closes cameronmaske#11
  • Loading branch information
cameronmaske committed Feb 26, 2015
1 parent dbce750 commit c5eb7aa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 17 additions & 1 deletion celery_once/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,22 @@ def now_unix():
return int(time())


def force_string(kwargs):
"""
Force key in dict or list to a string.
Fixes: https://github.com/TrackMaven/celery-once/issues/11
"""
if isinstance(kwargs, dict):
return {
force_string(key): force_string(value) for key, value in six.iteritems(kwargs)}
elif isinstance(kwargs, list):
return [force_string(element) for element in kwargs]
elif isinstance(kwargs, str) or isinstance(kwargs, unicode):
return str(kwargs)
else:
return kwargs


def kwargs_to_list(kwargs):
"""
Turns {'a': 1, 'b': 2} into ["a-1", "b-2"]
Expand All @@ -42,7 +58,7 @@ def kwargs_to_list(kwargs):
# Kwargs are sorted in alphabetic order.
# Taken from http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
for k, v in sorted(six.iteritems(kwargs), key=lambda kv: (str(kv[0]), str(kv[1]))):
kwargs_list.append(str(k) + '-' + str(v))
kwargs_list.append(str(k) + '-' + str(force_string(v)))
return kwargs_list


Expand Down
7 changes: 6 additions & 1 deletion tests/unit/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ def test_kwargs_to_list_4():
assert keys == ["boolean-True", "int-1", "list-[1, '2']", "str-abc"]


def test_kwargs_to_list_5():
keys = kwargs_to_list(
{'a': {u'b': 'c'}, 'list': [u'a', 'b'], u'zzz': 1})
assert keys == ["a-{'b': 'c'}", "list-['a', 'b']", "zzz-1"]


def test_queue_once_key():
key = queue_once_key("example", {})
assert key == "qo_example"
Expand All @@ -40,4 +46,3 @@ def test_queue_once_key_kwargs():
def test_queue_once_key_kwargs_restrict_keys():
key = queue_once_key("example", {'pk': 10, 'id': 10}, restrict_to=['pk'])
assert key == "qo_example_pk-10"

0 comments on commit c5eb7aa

Please sign in to comment.