【问题标题】:Python Unicode UnicodeEncodeErrorPython Unicode UnicodeEncodeError
【发布时间】:2009-07-03 02:33:04
【问题描述】:

我在尝试将 UTF-8 字符串转换为 unicode 时遇到问题。我得到了错误。

UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)

我尝试将其包装在 try/except 块中,但随后谷歌给了我一个系统管理员错误,这是一行。 有人可以建议如何捕获此错误并继续。

干杯,约翰。

-- 完全错误--

Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__
    handler.get(*groups)
  File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get
    self.redirect(url.long_url)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect
    self.response.headers['Location'] = str(absolute_url)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)

【问题讨论】:

    标签: python google-app-engine unicode utf-8


    【解决方案1】:

    正确的solution是这样做的:

    self.response.headers['Location'] = urllib.quote(absolute_url.encode("utf-8"))
    

    【讨论】:

    • 上面的注释是正确的代码。很抱歉没有正确地提出这个问题,我不是 100% 确切地知道我拥有什么类型的数据,因此没有完整的错误代码。谢谢你帮助亚历克斯。这应该修复 www.hurl.ws 的 URL 错误
    • @John,如果你想重定向然后你想重定向,我只是展示了如何正确编码和引用通用 Unicode URL;-)。出于好奇,您为什么接受这个(谢谢!)但不赞成?这是礼仪特有的……!-)
    【解决方案2】:

    您尝试设置的位置标头需要是一个 Url,并且一个 Url 需要在 Ascii 中。由于您的 Url 不是 Ascii 字符串,因此您会收到错误消息。由于 Location 标头不适用于无效的 Url,因此仅捕获错误无济于事。

    当您创建absolute_url 时,您需要确保它被正确编码,最好使用urllib.quote 和字符串encode() 方法。你可以试试这个:

    self.response.headers['Location'] = urllib.quote(absolute_url.encode('utf-8'))
    

    【讨论】:

      【解决方案3】:

      请编辑该混乱,使其清晰易读。提示:使用“代码块”(101010 按钮)。

      您说您正在“尝试将 UTF-8 字符串转换为 unicode”,但 str(absolute_url) 是一种奇怪的处理方式。你确定absolute_url 是UTF-8 吗?试试

      print type(absolute_url)
      print repr(absolute_url)
      

      如果它 UTF-8,你需要absolute_url.decode('utf8')

      【讨论】:

        【解决方案4】:

        试试这个:

        self.response.headers['Location'] = absolute_url.decode("utf-8")
        or
        self.response.headers['Location'] = unicode(absolute_url, "utf-8")
        

        【讨论】:

        • 抱歉没用。这是我当前的代码。因为我正在调用 self.redirect,所以字符串被编码并导致错误,因为在这种情况下,URL 实际上有一个“å”。如果发生此错误,那么我将 URL 写入页面,并使用 META-REFRESH 标记,让浏览器在几秒钟后进行重定向 self.redirect(url.long_url)
        • @zdmytriv: unicode(absolute_url)? UTF-8 不应该在某处提及吗?
        猜你喜欢
        • 2013-05-17
        • 1970-01-01
        • 2011-07-13
        • 2018-01-21
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        相关资源
        最近更新 更多