Python请求发送带有表单数据输入的POST请求

时间:2020-10-27 18:22:32

标签: python python-requests attachment form-data restapi

我有一个API向系统发送请求,我们正在将正文请求作为表单数据选项发送。

  1. 键:文档,值:sample.doc,类型:文件
  2. 键:请求,值:{“数据”:{“数字”:“ 17329937082”,“格式”:“ MSW”}},键入:文本

如何使用请求在Pyhton脚本中实现此目的。这在Postman中有效,我正尝试使用python脚本调用此API。

1 个答案:

答案 0 :(得分:1)

对于表单编码的数据,您需要将data kwarg与字典而不是字符串配对。为了演示其工作原理,我将使用requests.Request对象:

from requests import Request
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = Request('GET', 'https://my-url.com', data=data)
req = r.prepare()

r.headers
{'Content-Length': '80595', 'Content-Type': 'application/x-www-form-urlencoded'}

因此,在正常的请求中,它将看起来像:

import requests
import json

request_dict = {'Data': {'Number': "17329937082", "Format": "MSW"}}

data = {
    'Document': open('sample.doc', 'rb'),   # open in bytes-mode
    'Request': json.dumps(request_dict)     # formats the dict to json text
}

r = requests.get('my_url.com', data=data)
相关问题