Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload