为发布多部分/表单数据(包括文件和属性)而苦苦挣扎



我正在使用与具有良好文档API的服务器接口的程序的请求,除了使用多部分/表单数据(包括文件和属性(的文件上传。使用JSON的所有其他请求都不是问题。

文档说标头必须包含content-type:multipart/form-data但我已经意识到请求会自动执行此操作。然后,它以author.fullName: Heidi Walker的形式列出许多文本属性,然后以content: [physical file]的形式列出文件属性

我在邮递员中有一个工作示例,但我无法让它与请求一起使用。这是我的代码:

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 个错误。

另外,他们有什么方法可以查看请求的格式化正文吗?所以我可以检查边界标签是否已正确添加并与邮递员创建的内容进行比较?

我一直为此苦苦挣扎了很长时间,因此任何帮助将不胜感激。

更新:

我能够使用以下页面上概述的日志记录模块启用日志记录:https://requests.readthedocs.io/en/master/api/

检查我看到的请求正文:

Content-Disposition: form-data; name="author.fullName"; filename="author.fullName"rnrnFredrn

我想看到的(工作邮递员示例(是:

Content-Disposition: form-data; name="author.fullName"rnrnFredrn

似乎每一行都插入了filename="author.fullName"

终于可以正常工作了,如果其他人正在为此苦苦挣扎,这里是代码。

multi = MultipartEncoder(
fields={'author.fullName' : 'Automatic Upload',
'category.guid' : 'XXX',
'description' : 'Data Sheet',
'edition' : '01',
'format' : 'PDF',
'private' : 'false',
'storageMethodName' : 'FILE',
'title ' : title,
'content': (fileName, open(path, 'rb'), 'application/pdf')}
)
mpHeader = {
'Content-Type': multi.content_type,
'session_id':sID,
'cache-control': "no-cache",
}
resp = requests.post(url + '/files', headers = mpHeader, data = multi)

最新更新