2016-08-17 72 views
1

我想從python3客戶端發送文件到cherrypy。我正在使用請求庫。 我的客戶端代碼:CherryPy上傳文件

import requests 

url = 'http://127.0.0.1:8080/upload' 
files = {'file.zip': open('file.zip', 'rb')} 

r = requests.post(url, files=files) 

我的服務器代碼:

import os 
import tempfile 
import shutil 

import cherrypy 


config = { 
    'global' : { 
     'server.socket_host' : '127.0.0.1', 
     'server.socket_port' : 8080, 
     'server.thread_pool' : 8, 
     'server.max_request_body_size' : 0, 
     'server.socket_timeout' : 60 
    } 
} 


class App: 
    @cherrypy.config(**{'response.timeout': 3600}) 
    @cherrypy.expose() 
    def upload(self): 
     '''Handle non-multipart upload''' 

     destination = os.path.join('/home/uvv/upload') 
     with open(destination, 'wb') as f: 
      shutil.copyfileobj(cherrypy.request.body, f) 

     return 'Okay' 


if __name__ == '__main__': 
     cherrypy.quickstart(App(), '/', config) 

服務器返回錯誤:

127.0.0.1 - - [17/Aug/2016:11:38:49] "POST /upload HTTP/1.1" 400 2083 "" "python-requests/2.10.0" 
+0

這不是你發佈的錯誤,它是一個日誌條目。什麼是HTTP響應主體? P.S.嘗試在上傳處理程序的開始處添加日誌記錄以查看它是否被調用。 – webKnjaZ

+0

P.P.S.嘗試首先上傳小文件 – webKnjaZ

+0

並檢查您是否具有從cherrypy應用程序編寫'/ home/uvv/upload'文件的適當權限 – webKnjaZ

回答

2

這是有用的,從響應獲取信息。當您發送請求時,您會收到回覆。從這個響應中,您可以獲得有關HTTP代碼的信息,其中200代表正常,400代表錯誤請求。這是您可以在cherrypy日誌中看到的文本:POST /upload HTTP/1.1" 400。爲了獲得更多的信息,使用print(r.text)

#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 

import requests 

url = 'http://127.0.0.1:9090/upload' 
files = {'ufile': open('file.txt', 'rb')} 

r = requests.post(url, files=files) 

print(r) 
print(r.text) 

如果你使用上面的代碼波紋管的代碼,它的工作示例文件上傳到服務器的CherryPy的打印響應文本。

#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 

import os 
import cherrypy 

config = { 
    'global' : { 
     'server.socket_host' : '127.0.0.1', 
     'server.socket_port' : 9090, 
     'server.thread_pool' : 8, 
     'server.max_request_body_size' : 0, 
     'server.socket_timeout' : 60 
    } 
} 


class App: 

    @cherrypy.expose 
    def upload(self, ufile): 
     upload_path = os.path.normpath('/path/to/project/data/') 
     upload_file = os.path.join(upload_path, ufile.filename) 
     size = 0 
     with open(upload_file, 'wb') as out: 
      while True: 
       data = ufile.file.read(8192) 
       if not data: 
        break 
       out.write(data) 
       size += len(data) 
     out = ''' 
length: {} 
filename: {} 
mime-type: {} 
''' .format(size, ufile.filename, ufile.content_type, data) 
     return out 


if __name__ == '__main__': 
    cherrypy.quickstart(App(), '/', config) 

將路徑/path/to/project/data/替換爲適合您項目的路徑。