2009-07-03 80 views
1

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

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) 

回答

8

正确solution是做到以下几点:

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

试试这个:

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

比较遗憾的是没有工作。 这是我现在的代码。因为我调用self.redirect,字符串正在编码并导致错误,因为在这种情况下,URL实际上有一个“å”。如果发生此错误,那么我将网址写入页面,并使用META-REFRESH标记,让浏览器在几秒钟后重定向 self.redirect(url.long_url) – 2009-07-03 02:45:11

+0

@zdmytriv:unicode(absolute_url)?不应该在某处提到UTF-8吗? – 2009-07-03 02:53:05

1

请编辑一塌糊涂,这样它的清晰。提示:使用“代码块”(101010 thingy按钮)。

你说你是“试图将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

位置的头部,你试图设置需要有一个网址和一个网址需要在ASCII。由于你的Url不是一个Ascii字符串,你会得到这个错误。由于位置标题不适用于无效的网址,因此抓取错误将无济于事。

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

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