【发布时间】:2020-03-25 22:27:15
【问题描述】:
我正在将请求用于与具有良好记录的 API 的服务器接口的程序,但文件上传除外,它使用多部分/表单数据,包括文件和属性。使用 JSON 的所有其他请求都不是问题。
文档说标头必须包含content-type:multipart/form-data,但我已经意识到请求会自动执行此操作。然后它以author.fullName: Heidi Walker 的形式列出了一些文本属性,然后以content: [physical file] 的形式列出了一个文件属性
我在 Postman 中有一个工作示例,但我无法让它与 Requests 一起使用。这是我的代码:
header = {
'session_id':sID,
}
# These are the required text attributes from the API docs + the actual file
fileInfo = {
'author.fullName' : 'Fred',
'category.guid' : 'xxx',
'description' : 'Data Sheet',
'format' : 'PDF',
'private' : 'false',
'storageMethodName' : 'FILE',
'title ' : 'Test Datasheet',
'content': open(path, 'rb')
}
resp = requests.post(url + '/files', headers = header, files = fileInfo)
我不断从服务器收到 400 个错误。
另外,他们是否可以通过任何方式查看请求的格式化正文?所以我可以检查边界标签是否已正确添加并与 Postman 创建的内容进行比较?
我一直在努力解决这个问题,所以任何帮助都将不胜感激。
更新:
我能够使用本页所述的日志记录模块启用日志记录:https://requests.readthedocs.io/en/master/api/
检查我看到的请求正文:
Content-Disposition: form-data; name="author.fullName"; filename="author.fullName"\r\n\r\nFred\r\n
我希望看到的(工作邮递员示例)是:
Content-Disposition: form-data; name=\"author.fullName\"\r\n\r\nFred\r\n
似乎每一行都插入了filename="author.fullName"。
【问题讨论】:
标签: python-3.x https python-requests