ValueError:数据不能是字符串 [英] ValueError: Data must not be a string

查看:26
本文介绍了ValueError:数据不能是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 requests 执行以下操作:

I am trying to do the following with requests:

data = {'hello', 'goodbye'}
json_data = json.dumps(data)
headers = {
        'Access-Key': self.api_key,
        'Access-Signature': signature,
        'Access-Nonce': nonce,
        'Content-Type': 'application/json',
        'Accept': 'text/plain'
    }
r = requests.post(url, headers=headers, data=json_data, 
                 files={'file': open('/Users/david/Desktop/a.png', 'rb')})

但是,我收到以下错误:

However, I get the following error:

ValueError: Data must not be a string.

请注意,如果我删除 files 参数,它会根据需要工作.如果包含 files,为什么 requests 不允许我发送数据的 json 编码字符串?

Note that if I remove the files parameter, it works as needed. Why won't requests allow me to send a json-encoded string for data if files is included?

请注意,如果我将 data 更改为普通的 Python 字典(而不是 json 编码的字符串),则上述方法有效.所以问题似乎是,如果文件不是 json 编码的,那么数据就不能是 json 编码的.但是,我需要对我的数据进行编码以匹配 API 创建的哈希签名.

Note that if I change data to be just the normal python dictionary (and not a json-encoded string), the above works. So it seems that the issue is that if files is not json-encoded, then data cannot be json-encoded. However, I need to have my data encoded to match a hash signature that's being created by the API.

推荐答案

当您将正文指定为 JSON 字符串时,您不能再附加文件,因为文件上传需要 MIME 类型 multipart/form-data.

When you specify your body to a JSON string, you can no longer attach a file since file uploading requires the MIME type multipart/form-data.

您有两个选择:

  1. 将您的 JSON 字符串封装为表单数据的一部分(类似于 json => json.dumps(data))
  2. 以 Base64 编码您的文件并将其传输到 JSON 请求正文中.这看起来工作量很大.

这篇关于ValueError:数据不能是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆