【问题标题】:python requests issues with non ascii datapython请求非ascii数据的问题
【发布时间】:2014-06-18 07:04:30
【问题描述】:

我在尝试使用请求作为附件发送的文件中使用非 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 数据(希伯来语)。 图像中可以看到的异常是:

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

【问题讨论】:

    标签: python http encoding python-requests mailgun


    【解决方案1】:

    open() 函数 has a parameter encoding,像 f = open('t.txt', encoding='utf-8') 一样使用,它接受文档中所述的 a variety of parameters。找出您的数据使用的编码方案(可能是 UTF-8)并查看使用该编码打开是否有效。

    【讨论】:

      【解决方案2】:

      不要使用 encoding 参数打开文件,因为您想将它们作为二进制数据打开。打开的调用应该类似于open(f, 'rb')。请求的文档只是有意地展示了这样的例子,甚至记录了这种行为。

      【讨论】:

        猜你喜欢
        • 2014-08-15
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 2014-06-20
        • 2017-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多