【问题标题】:Python requests to send POST request with form-data inputPython 请求发送带有表单数据输入的 POST 请求
【发布时间】:2020-10-27 18:22:32
【问题描述】:

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

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

如何在 Pyhton 脚本中使用 Requests 实现这一点。这在 Postman 中有效,我正在尝试使用 python 脚本调用此 API。

【问题讨论】:

  • 你有read the docs?你在哪里卡住了吗?
  • 我将这个“r = requests.get('api.github.com/events')”用于正常请求,但不确定将什么用于“form-data”正文请求。我尝试了 Multipart-Encoded,但它给出了 415 unsupported media type error 作为响应
  • 你做了什么来尝试多部分编码?您确定端点需要表单编码的数据吗?还是期待json?
  • 这是 Json 响应。抱歉,我不知道该用什么,只是在多部分中尝试了一些东西。在 python 中发出表单数据请求的最佳解决方案是什么?

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


【解决方案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)

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2021-06-03
    • 2015-10-05
    • 2022-11-19
    • 2020-11-18
    相关资源
    最近更新 更多