Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Python UTF-8-capable urlencode

By: a guest on Mar 10th, 2010  |  syntax: Python  |  size: 0.60 KB  |  views: 199  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. def utf8_urlencode(params):
  2.     """ A urlencode that handles special characters better than the
  3.    urllib.urlencode function.
  4.    """
  5.     return u'&'.join([u'%s=%s' % (utf8_quote(key), utf8_quote(value))
  6.                       for key, value in params.iteritems()])
  7.  
  8. default_safe = u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-'
  9. def utf8_quote(s, safe=u''):
  10.     safe = default_safe + safe
  11.     urlenc = u''
  12.     for c in s.encode(u'utf-8').decode(u'iso-8859-1'):
  13.         if c in safe:
  14.             urlenc += c
  15.         else:
  16.             urlenc += u'%%%2x' % ord(c)
  17.     return urlenc