【问题标题】:How to send multiple form parameters in request?如何在请求中发送多个表单参数?
【发布时间】:2017-09-05 06:50:24
【问题描述】:

我正在做一个需要指定多个表单参数的项目,其中一个是文件本身。

我尝试了什么:

import requests
REST_URL = 'http://192.168.150.138:8888/tasks/create/file'
with open(os.path.join('/home/default/Batch/Samples/', filename),'rb') as sample:
          files = {'file'  :("temp_file_name" , sample)}
          r = requests.post(REST_URL , files=files)

问题

我需要像这样传递附加信息(所有这些都是表单参数)

file (required) - sample file (multipart encoded file content)
package (optional) - analysis package to be used for the analysis
timeout (optional) (int) - analysis timeout (in seconds)
priority (optional) (int) - priority to assign to the task (1-3)
options (optional) - options to pass to the analysis package
machine (optional) - label of the analysis machine to use for the analysis
platform (optional) - name of the platform to select the analysis machine from (e.g. “windows”)

假设如果我想发送机器名称,我可以这样创建吗?

data = {'machine' :'machine_name'}
r =requests.post(EST_URL , files=files,data=data)

任何建议都会有所帮助。

【问题讨论】:

  • 是的,导入请求
  • @das-g 类型已更正

标签: python python-2.7 python-3.x request python-requests


【解决方案1】:

问题:假设如果我想发送机器名称,我可以这样创建吗?


请求快速入门More complicated POST requests

如果要测试requests参数可以运行如下:

import requests, io
url = 'http://httpbin.org/anything'

sample = io.StringIO('lorem ipsum')
files = {'file': ("temp_file_name", sample)}
data = {'machine': 'machine_name'}
r = requests.post(url, data=data, files=files)

r_dict = r.json()
for key in r_dict:
    print('{}:{}'.format(key, r_dict[key]))

输出

json:None
headers:{'Connection': 'close', 'Content-Length': '261', 'User-Agent': 'python-requests/2.11.1', 'Content-Type': 'multipart/form-data; boundary=5ed95afb5ea2437eade92a826b29be0d', 'Host': 'httpbin.org', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*'}
data:
args:{}
files:{'file': 'lorem ipsum'}
method:POST
url:http://httpbin.org/anything
form:{'machine': 'machine_name'}

查看http://httpbin.org,还有很多其他url端点可以测试。

用 Python 测试:3.4.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-06-02
    • 2021-06-06
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    相关资源
    最近更新 更多