导入时的UnicodeDecodeError(tweepy)

时间:2011-09-12 19:07:08

标签: python unicode tweepy

我试图在tweepy中使用函数“update_profile_background_image”并收到错误:

Traceback (most recent call last):
  File "XXX.py", line 1401, in <module>
    psn_card.gen_twitter_bg(user_db)
  File "XXX.py", line 972, in gen_twitter_bg
    auth_api.update_profile_background_image(file)
  File "build/bdist.linux-x86_64/egg/tweepy/api.py", line 346, in update_profile_background_image
    headers, post_data = API._pack_image(filename, 800)
  File "build/bdist.linux-x86_64/egg/tweepy/api.py", line 729, in _pack_image
    body = '\r\n'.join(body)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)
问题是:这个lib是一个egg文件,我怎么解决这个问题? 这是一个关于tweepy的错误吗?

该功能是读取文件(图像)并通过POST(http)发送到twitter api。

在我尝试操作加载的图像时发生错误。

我的所有.py都配置为使用utf-8:

# -- coding: utf-8 --

1 个答案:

答案 0 :(得分:4)

我的猜测是filename是一个Unicode字符串。不幸的是,Tweepy不支持Unicode文件名。这是一个错误吗?可以说

问题是它尝试使用Unicode字符串逐字创建HTTP POST数据,而不是将其编码为字节字符串:

body.append('Content-Disposition: form-data; name="image"; filename="%s"' % filename)

这使得body列表中的一个字符串成为Unicode字符串,并且当序列中的一个字符串是Unicode字符串并且您尝试join()时,结果最终为Unicode。但是,HTTP POST主体是一个带有二进制gunk的字节字符串,因此它不是ASCII兼容的,因此尝试将其隐式强制转换为Unicode失败。

(在任何情况下,Content-Disposition中给出的文件名绝对不应该包含完整路径,如上面的代码那样。我建议在上面的行中使用filename= os.path.basename(filename).encode('us-ascii', 'ignore')之类的内容作为第一次快速解决。我不确定Twitter是否关心文件名是什么,尽管......)

相关问题