1

我试图在 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)

问题是:这个库在一个鸡蛋文件中,我如何解决这个问题?这是 tweepy 上的错误吗?

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

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

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

# -- coding: utf-8 --
4

1 回答 1

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 正文是一个字节字符串,其中包含大量二进制垃圾,因此它与 ASCII 不兼容,因此尝试将其隐式强制转换为 Unicode 失败。

(无论如何,给出的文件名Content-Disposition绝对不应该包含完整的路径,就像上面的代码一样。我建议filename= os.path.basename(filename).encode('us-ascii', 'ignore')在上面的行中作为第一个快速修复。我不确定 Twitter 是否关心文件名是什么,虽然......)

于 2011-09-12T21:01:25.180 回答