python 同时发多个请求_如何在python中发送包含请求的“多部分/表单数据”?

本文介绍了如何在Python中使用requests库发送包含请求的多部分/表单数据,包括上传文件和表单字段。示例代码展示了使用files参数和MultipartEncoder进行多部分请求的方法,以及处理相同名称字段的技巧。
摘要由CSDN通过智能技术生成

您需要使用files参数发送多部分表单POST请求。平当你不需要上传任何文件。

原著请求资料来源:def request(method, url, **kwargs):

"""Constructs and sends a :class:`Request `.

...

:param files: (optional) Dictionary of ``'name': file-like-objects``

(or ``{'name': file-tuple}``) for multipart encoding upload.

``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,

3-tuple ``('filename', fileobj, 'content_type')``

or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,

where ``'content-type'`` is a string

defining the content type of the given file

and ``custom_headers`` a dict-like object

containing additional headers to add for the file.

有关部分是:file-tuple can be a2-tuple, 3-tupleor a4-tuple.

基于上述,包含上传文件和表单字段的最简单的多部分表单请求如下所示:multipart_form_data = {

'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),

'action': (None, 'store'),

'path': (None, '/path1')}response = requests.post('https://httpbin.org/post', files=multipart_form_data)print(response.content)

☝ 注意None作为纯文本字段元组中的第一个参数,这是文件名字段的占位符,它仅用于文件上载,但用于传递文本字段。None因为需要第一个参数才能提交数据。

如果这个api不足以满足您的需要,或者您需要以相同的名称发布多个字段,那么请考虑使用请求工具带 (pip install requests_toolbelt),它是核心请求模块,该模块提供对文件上载流以及多部分编码器可以用来代替files,它接受作为字典和元组的参数。

MultipartEncoder既可用于多部分请求,也可用于实际上载字段之外的请求。它必须分配给data参数。import requestsfrom requests_toolbelt.multipart.encoder import MultipartEncodermultipart_data = MultipartEncoder(

fields={

# a file upload field

'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')

# plain text fields

'field0': 'value0',

'field1': 'value1',

}

)response = requests.post('http://httpbin.org/post', data=multipart_data,

headers={'Content-Type': multipart_data.content_type})

如果需要发送多个名称相同的字段,或者表单字段的顺序很重要,则可以使用元组或列表来代替字典,即:multipart_data = MultipartEncoder(

fields=(

('action', 'ingest'),

('item', 'spam'),

('item', 'sausage'),

('item', 'eggs'),

)

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值