如何使用发布多部分/表单数据的请求来排列数据和文件的顺序? [英] How to arrange the order of data and file using requests to post multipart/form-data?

查看:60
本文介绍了如何使用发布多部分/表单数据的请求来排列数据和文件的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数据前面排列文件.如果尝试传统方式,数据将显示在文件前面.更具体地说,我希望myfile出现在form_value之前.

I want to arrange file in front of data. If I try the traditional way, the data appears in front of file. To be more specifically, I want myfile to appear before form_value.

form_value={'exp':'python', 'ptext':'text', 'board':'Pictures'}
myfile = {'up': ('aa.png', open('aa.png', 'rb'), 'image/png')}
r = requests.post(url, files=myfile, data=form_value, cookies=cookie)

结果

Content-Type: multipart/form-data; boundary=170e4a5db6d74d5fbb384dfd8f2d33ce

--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="ptext"

text
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="board"

Pictures
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="exp"

python
--170e4a5db6d74d5fbb384dfd8f2d33ce
Content-Disposition: form-data; name="up"; filename="aa.png"
Content-Type: image/png

推荐答案

requests总是将files放在data之后,但是您可以将data参数添加到files参数中.

requests always places files after data, but you can add your data parameters to the files argument instead.

然后,您必须使用带有键值元组的列表,而不是字典,以保留顺序.并且您需要提供文件名和内容类型条目作为None,以确保requests不会尝试为您提供错误的标题:

You then do have to use a list with key-value tuples, instead of a dictionary, to preserve order. And you need to provide the filename and content type entries as None to make sure that requests doesn't try and give you the wrong headers:

files = [
    ('up', ('aa.png', open('aa.png', 'rb'), 'image/png')),
    ('exp', (None, 'python', None)),
    ('ptext', (None, 'text', None)),
    ('board', (None, 'Pictures', None)),
]

r = requests.post(url, files=files, cookies=cookie)

这将产生:

Content-Type: multipart/form-data; boundary=6f9d948e26f140a289a9e8297c332a91

--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="up"; filename="aa.png"
Content-Type: image/png

[ .. image data .. ]

--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="exp"

python
--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="ptext"

text
--0ca5f18576514b069c33bc436ce6e2cd
Content-Disposition: form-data; name="board"

Pictures
--0ca5f18576514b069c33bc436ce6e2cd--

这篇关于如何使用发布多部分/表单数据的请求来排列数据和文件的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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