如何在GAE(python)中解码encodeURIComponent?

时间:2012-03-26 21:30:57

标签: python google-app-engine unicode character-encoding uri

我有一个使用JS encodeURIComponent在客户端编码的unicode字符串。

如果我在本地使用Python中的以下内容,我会得到预期的结果:

>>> urllib.unquote("Foo%E2%84%A2%20Bar").decode("utf-8")
>>> u'Foo\u2122 Bar'

但是当我在Google App Engine中运行时,我得到:

Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 703, in __call__
    handler.post(*groups)
  File "/base/data/home/apps/s~kaon-log/2.357769827131038147/main.py", line 143, in post
    path_uni = urllib.unquote(h.path).decode('utf-8')
  File "/base/python_runtime/python_dist/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

我仍在使用Python 2.5,以防万一。我错过了什么?

2 个答案:

答案 0 :(得分:9)

我的猜测是h.path是一个unicode对象。然后urllib.unquote将返回一个unicode对象。首先在unicode对象上调用decode时,使用默认编码(ascii)将其转换为str,然后在此处获得'ascii' codec can't encode异常。

这是一个证据:

>>> urllib.unquote(u"Foo%E2%84%A2%20Bar").decode("utf-8")
...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

这应该有效:

urllib.unquote(h.path.encode('utf-8')).decode("utf-8")

有一个stackoverflow线程解释了为什么unicode不能与urllib.unquote一起使用:How to unquote a urlencoded unicode string in python?

答案 1 :(得分:0)

使用此类而不是urllib2:

class URL(object):
  '''encode/decode requested URL'''
  def __init__(self):
    self.charset = '/abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.'

  def encode(self,url):
    return ''.join([c if c in self.charset else '%'+c.encode('hex').upper() for c in url])

  def decode(self,url):
    return re.compile('%([0-9a-fA-F]{2})',re.M).sub(lambda m: chr(int(m.group(1),16)), url)

示例:

  import re
  URL().decode(your URL)