2017-09-05 73 views
0

Iam在一個需要指定多個表單參數的項目上工作,其中一個是文件本身。如何在請求中發送多個表單參數?

我的嘗試:

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) 

任何建議將有所幫助。

+0

是,導入請求 –

+0

@ DAS-G型修正 –

回答

0

問題:假設如果我想發送機器名稱的形式也可以創建像這樣嗎?


請求快速入門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

相關問題