Skip to content

Commit

Permalink
Add support for unicode when creating uuid
Browse files Browse the repository at this point in the history
The uuid module differs in support for unicode between python 2 and
3. This should correctly handle either unicode or byte strings.
  • Loading branch information
Mike Graves committed Jan 26, 2016
1 parent 94e875f commit 296995e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 13 additions & 2 deletions slingshot/app.py
Expand Up @@ -34,8 +34,15 @@ def submit(archive, url):


def make_uuid(value, namespace):
ns = uuid.uuid5(uuid.NAMESPACE_DNS, namespace)
uid = uuid.uuid5(ns, value)
try:
ns = uuid.uuid5(uuid.NAMESPACE_DNS, namespace)
uid = uuid.uuid5(ns, value)
except UnicodeDecodeError:
# Python 2 requires a byte string for the second argument.
# Python 3 requires a unicode string for the second argument.
value, namespace = [_bytes(s) for s in (value, namespace)]
ns = uuid.uuid5(uuid.NAMESPACE_DNS, namespace)
uid = uuid.uuid5(ns, value)
return str(uid)


Expand All @@ -61,3 +68,7 @@ def temp_archive(data, name):
def sub_dirs(directory):
return [d for d in os.listdir(directory)
if os.path.isdir(os.path.join(directory, d))]


def _bytes(value):
return bytearray(value, 'utf-8')
5 changes: 5 additions & 0 deletions tests/test_app.py
Expand Up @@ -53,6 +53,11 @@ def test_make_uuid_creates_uuid_string():
'aabfaa4e-15a2-51b5-a684-46c530cb0263'


def test_make_uuid_works_with_unicode_values():
assert make_uuid('grayscale', u'arrowsmith.mit.edu') == \
'aabfaa4e-15a2-51b5-a684-46c530cb0263'


def test_sub_dirs_returns_list_of_sub_directories():
d = tempfile.mkdtemp()
os.mkdir(os.path.join(d, 'foo'))
Expand Down

0 comments on commit 296995e

Please sign in to comment.