我试图使用的功能"update_profile_background_image"在tweepy和得到的错误:
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 = 'rn'.join(body)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)
的问题是:这个库是在一个鸡蛋文件,我如何解决这个问题?这是tweepy上的bug吗?
该函数读取文件(图像)并通过POST (http)发送到twitter api。
当我试图操作加载的图像时,错误发生了。
我所有的.py都配置为使用utf-8:
# -- coding: utf-8 --
我猜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甚至关心文件名是什么,尽管…)