2017-06-02 20 views
-6

我有一個Rails應用服務器。我想建立一個上傳圖片的Python客戶端。如何使用python-request在Rails應用上發佈文件

我想要做這樣的事情:

def add_photo(entry_id, image_path): 

    return requests.post(
     url  = URL, 
     headers = HEADER, 
     json = { 
      'entry': { 
       'entry_id': entry_id, 
      } 
     }, 
     files = { 
      "entry['photo']": (
       os.path.basename(image_path), 
       open(image_path, 'rb'), 
       'image/jpg', 
       {'Expires': '0'} 
      ) 
     } 
    ) 

我需要嵌套到「項」鍵的圖像。以上代碼無效,因爲密鑰"entry['photo']"無效。

我該怎麼做?

非常感謝您的幫助!

+0

如果你要向下投票這個, 請告訴我爲什麼?謝謝! – JPN

+0

目前尚不清楚你要求什麼。你想看看接受圖像的Rails代碼,或者發送它的Python代碼,或者兩者兼而有之?如果您描述了您嘗試了哪些內容,特別是您是否受到了障礙,並且您收到了任何錯誤消息,這也會有所幫助。 – Troy

+0

讓我知道問題編輯是否清楚。謝謝! – JPN

回答

0

我想通了:

def add_photo(entry_id, image_path): 

    return requests.post(
     url  = URL, 
     headers = HEADER, 
     files = { 
      'entry[entry_id]': (None, entry_id, 'text'), 
      'entry[photo]': (os.path.basename(image_path), open(image_path, 'rb'), 'image/jpg', {'Expires': '0'}) 
     } 
    ) 
0

評論:我需要的圖片的關鍵是進入[「照片」。

你想要做的結果無效dict什麼。以下是從docs.python-requests.org

files = {'photo': ('test.jpg', open('test.jpg', 'rb'), 'image/jpg', {'entry_id': entry_id, 'Expires': '0'})} 

從這麼回答Upload Image using POST form data in Python-requests

files = {'media': open('test.jpg', 'rb')} 
requests.post(url, files=files) 
+0

在這個例子中,圖像的關鍵是'media'。我需要圖像的關鍵是'進入'['照片']'。我需要這個圖像是兩層深的。 – JPN

+0

是的,無效的字典...這是問題所在。我如何解決這個問題? – JPN

相關問題