2015-11-04 47 views
0

我找不到一個如何在python中設置http服務器的示例,它將文件保存到使用HTTP POST和urllib2發送到的目錄,請求或捲曲。python - 如何使用basehttpserver保存使用POST發送的文件

我想將其用作客戶端分析數據並將結果文件發送回服務器的程序的一部分。服務器將文件保存到分析結果的目錄中。

謝謝

+0

https://snipt.net/raw/f8ef141069c3e7ac7e0134c6b58c25bf/?nice – mguijarr

回答

0

我最近在Python中使用CGI模塊做了這個。 我的POST方法和文件複製過程如下。 它使用一個表單,其中sfname是文件必須保存的完整路徑,file是文件本身。這比你需要的稍微複雜一些,但它會讓你走。

def do_POST(self): 
    f = StringIO() 
    fm = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST'}) 
    if "file" in fm: 
     r, resp, info = self.get_file_data(fm) 
     print r, info, "by: ", self.client_address 
     if r: 
      f.write("File upload successful: %s" % info) 
      f.seek(0) 
      if resp == 200: 
       # Do stuff here 
      else: 
       # Error handle here 
     else: 
      f.write("File upload failed: %s" % info) 
      f.seek(0) 
      if resp == 200: 
       # Do stuff here 
      else: 
       # Error handle here 
     if f: 
      copyfileobj(f, self.wfile) 
      f.close() 
    else: 
     # Error handle here 

def get_file_data(self, form): 
    fn = form.getvalue('sfname') 
    fpath, fname = ospath.split(fn) 
    if not ospath.isabs(fpath): 
     return (False, 400, "Path of filename on server is not absolute") 
    if not ospath.isdir(fpath): 
     return (False, 400, "Cannot find directory on server to place file") 
    try: 
     out = open(fn, 'wb') 
    except IOError: 
     return (False, 400, "Can't write file at destination. Please check permissions.") 
    out.write(form['file'].file.read()) 
    return (True, 200, "%s ownership changed to user %s" % (fn, u)) 

此外,這是我導入的包。你可能不需要所有的人。

from shutil import copyfileobj 
from os import path as ospath 
import cgi, 
import cgitb; cgitb.enable(format="text") 
try: 
    from cStringIO import StringIO 
except ImportError: 
    from StringIO import StringIO 

我用curl -F "[email protected]/myfile.txt" -F "sfname=/home/user/myfile.txt" http://myserver測試它,它工作正常。不能保證其他方法。希望這可以幫助。

+0

感謝隊友,讓它工作。 – budge

+0

你可以請upvote或標記爲正確的?我想在這裏建立一些代表... ;-) – Munir

相關問題