python - 导入时出现 UnicodeDecodeError (tweepy)

标签 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)

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

函数是读取一个文件(图片)并通过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 是否关心文件名是什么。 ..)

关于python - 导入时出现 UnicodeDecodeError (tweepy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392693/

相关文章:

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\u2026'

ios - UITextField 中的自定义图像,如 Venmo 应用程序

python - 努力在Python中显示阿拉伯语推文

python - Tweepy 2.0 卡在 ssl do_handshake() 上

python - 如何获取字典中多个最小/最大值?

python - 返回 Unicode 字符串与返回编码为 UTF-8 的普通字符串?

python - 使用 MatplotLib python 的交互式堆积条形图

java - 为什么我所有的解码字符串最后都有 '?'? Java 字符串解码

python - 使用 struct.pack 和 python 创建数据包

python - Google Cloud Python灵活环境多线程数据库 worker 卡住