diff options
author | Ian Cordasco <graffatcolmingov@gmail.com> | 2016-08-17 16:21:16 -0500 |
---|---|---|
committer | Ian Cordasco <graffatcolmingov@gmail.com> | 2016-08-17 16:21:16 -0500 |
commit | 2b5c704bf6f33f3dc375db296690f0321bb2f260 (patch) | |
tree | 22fee569428d4cea3cb96385ef4865d4547b6859 /uritemplate | |
parent | 925ffa28d44f701c3831340c46151078656eef2c (diff) | |
download | platform_external_python_uritemplates-2b5c704bf6f33f3dc375db296690f0321bb2f260.tar.gz platform_external_python_uritemplates-2b5c704bf6f33f3dc375db296690f0321bb2f260.tar.bz2 platform_external_python_uritemplates-2b5c704bf6f33f3dc375db296690f0321bb2f260.zip |
Fix handling of unicode values for Python 2
Closes #19
Diffstat (limited to 'uritemplate')
-rw-r--r-- | uritemplate/variable.py | 34 |
1 files changed, 28 insertions, 6 deletions
diff --git a/uritemplate/variable.py b/uritemplate/variable.py index a47bf0a..1842830 100644 --- a/uritemplate/variable.py +++ b/uritemplate/variable.py @@ -15,12 +15,13 @@ What do you do? """ -try: - from urllib import quote -except ImportError: - # python 3 - from urllib.parse import quote import collections +import sys + +if (2, 6) <= sys.version_info < (2, 8): + import urllib +elif (3, 3) <= sys.version_info < (4, 0): + import urllib.parse as urllib class URIVariable(object): @@ -174,7 +175,7 @@ class URIVariable(object): if value: value = value[:prefix] if prefix else value - return '%s=%s' % (name, quote(str(value), safe)) + return '%s=%s' % (name, quote(value, safe)) return name + '=' def _label_path_expansion(self, name, value, explode, prefix): @@ -360,3 +361,24 @@ def list_test(value): def dict_test(value): return isinstance(value, (dict, collections.MutableMapping)) + + +try: + texttype = unicode +except NameError: # Python 3 + texttype = str + +stringlikes = (texttype, bytes) + + +def _encode(value, encoding='utf-8'): + if (isinstance(value, texttype) and + getattr(value, 'encode', None) is not None): + return value.encode(encoding) + return value + + +def quote(value, safe): + if not isinstance(value, stringlikes): + value = str(value) + return urllib.quote(_encode(value), safe) |