2015-04-12 70 views
3

我試圖使用請求庫將圖片上傳到python-eve服務器。爲了做到這一點,我發送了一個multipart/form-data請求。這似乎是對我的架構問題,它看起來像這樣:使用請求將文件上傳到python-eve

schema = { 
    'name': { 
     'type': 'string', 
     'required': True 
    }, 
    'description': { 
     'type': 'string' 
    }, 
    'picture': { 
     'type': 'media' 
    }, 
    'properties': { 
     'type' : 'dict' 
    } 
} 

的要求是這樣的:

import requests 

file = open('/home/user/Desktop/1500x500.jpeg', 'rb') 
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}} 
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file}) 

我得到的是一個ResourceInvalid例外:

ResourceInvalid: Failed. Response status: 422. Response message: UNPROCESSABLE ENTITY. Error message: {"_status": "ERR", "_issues": {"properties": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}} 

有沒有解決方案?我錯過了有關請求格式的內容嗎?

回答

2

像這樣的東西應該只是罰款:

import requests 

file = open('/home/user/Desktop/1500x500.jpeg', 'rb') 
payload = {'name': 'hello'} 

r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file}) 
+0

這樣的作品,但什麼是失敗的是: 有效載荷= { '名': '你好', '性':{ '爲prop1': '值', 'PROP2': '其他'}} r = requests.post(「http:// localhost:5001/node」,data = payload,files = {'picture':file}) 詞典的值。 – fsiddi

+0

「屬性」字段的定義是什麼? –

+0

模式中只是一個'字典'類型。我目前沒有執行任何內容/驗證。 – fsiddi

3

我剛纔也有類似的issue。我建議你試着改變你的代碼:將你的字典轉儲到一個json對象中,並添加一個頭來描述你發送的內容。

import requests 
import json 

file = open('/home/user/Desktop/1500x500.jpeg', 'rb') 
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}} 
headers = {'Content-type': 'application/json; charset=utf-8'} 
r = requests.post("http://localhost:5001/node", data=json.dumps(payload), files={'picture': file}, headers=headers) 
+0

是的,這很可能是問題所在。謝謝。 –

+0

感謝您的建議!這些代碼在你那正常嗎? 從我一直在閱讀的內容中,當使用application/json Content-type進行請求時,無法發送文件對象(二進制數據)。唯一的辦法就是base64對文件進行編碼並以這種方式發送,但是這會迷惑Eve。 請讓我知道你是否設法讓代碼運行,因爲對我來說它失敗了。 – fsiddi