1

我在尝试使用请求作为附件发送的文件中使用非 ascii 字符时遇到问题。

_send_output 函数中的 httplib 模块出现异常。看这张图片:

在此处输入图像描述

这是我的代码:

response = requests.post(url="https://api.mailgun.net/v2/%s/messages" % utils.config.mailDomain,
                auth=("api", utils.config.mailApiKey),
                data={
                        "from" : me,
                        "to" : recepients,
                        "subject" : subject,
                        "html" if html else "text" : message
                    },
                files= [('attachment', open(f)) for f in attachments] if attachments and len(attachments) else []   


            )

问题在于包含非 ascii 数据(希伯来语)的 files 参数。图像中可以看到的异常是:

UnicodeDecodeError:“ascii”编解码器无法解码位置 673 中的字节 0xd0:序数不在范围内(128)

4

2 回答 2

1

open()函数有一个参数 encoding,用于f = open('t.txt', encoding='utf-8')接受文档中概述的各种参数。找出您的数据使用的编码方案(可能是 UTF-8),并查看使用该编码打开是否有效。

于 2014-06-18T07:24:33.140 回答
0

不要使用 encoding 参数打开文件,因为您想将它们作为二进制数据打开。打开的调用应该是这样的open(f, 'rb')。请求的文档仅故意显示此类示例,甚至记录此行为。

于 2014-06-19T00:14:30.413 回答