【问题标题】:python - How do use basehttpserver to save files sent using POSTpython - 如何使用 basehttpserver 保存使用 POST 发送的文件
【发布时间】:2016-02-04 15:50:16
【问题描述】:

我找不到如何在 python 中设置 http 服务器的示例,它将文件保存到使用带有 urllib2、请求或 curl 的 HTTP POST 发送给它的目录。

我想将它用作客户端分析数据并将结果文件发送回服务器的程序的一部分。服务器将文件保存到分析结果的目录中。

谢谢

【问题讨论】:

标签: python http post server


【解决方案1】:

我最近使用 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 "file=@./myfile.txt" -F "sfname=/home/user/myfile.txt" http://myserver 对其进行了测试,它运行良好。不能保证其他方法。希望这会有所帮助。

【讨论】:

  • 您可以点赞或标记为正确吗?我正在尝试在这里建立一些代表... ;-)
猜你喜欢
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多