If I have an object like:
d = {'a':1, 'en': 'hello'}
...then I can pass it to urllib.urlencode, no problem:
percent_escaped = urlencode(d)
print percent_escaped
But if I try to pass an object with a value of type unicode, game over:
d2 = {'a':1, 'en': 'hello', 'pt': u'olá'}
percent_escaped = urlencode(d2)
print percent_escaped # This fails with a UnicodeEncodingError
So my question is about a reliable way to prepare an object to be passed to urlencode.
I came up with this function where I simply iterate through the object and encode values of type string or unicode:
def encode_object(object):
for k,v in object.items():
if type(v) in (str, unicode):
object[k] = v.encode('utf-8')
return object
This seems to work:
d2 = {'a':1, 'en': 'hello', 'pt': u'olá'}
percent_escaped = urlencode(encode_object(d2))
print percent_escaped
And that outputs a=1&en=hello&pt=%C3%B3la, ready for passing to a POST call or whatever.
But my encode_object function just looks really shaky to me. For one thing, it doesn't handle nested objects.
For another, I'm nervous about that if statement. Are there any other types that I should be taking into account?
And is comparing the type() of something to the native object like this good practice?
type(v) in (str, unicode) # not so sure about this...
Thanks!