从通过Python实现的简单HTTP服务器下载文件

问题描述 投票:0回答:2

我有一个使用Python的HTTP服务器,它能够接收和保存通过POST请求发送的文件。但是,现在我正在尝试使用GET请求下载请求的文件。基本上,我想发送带有文件名的GET请求,并且希望服务器为我提供要下载的文件。我该怎么办?

到目前为止,我的代码:

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

def _html(self, message):
    """This just generates an HTML document that includes `message`
    in the body. Override, or re-write this do do more interesting stuff.
    """
    content = f"<html><body><h1>{message}</h1></body></html>"
    return content.encode("utf8")  # NOTE: must return a bytes object!

def do_GET(self):
    self._set_headers()
    self.wfile.write(self._html("hi!"))

def do_HEAD(self):
    self._set_headers()

def do_POST(self):
    form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={'REQUEST_METHOD':'POST',
                 'CONTENT_TYPE':self.headers['Content-Type'],
                 })
    filename = form['file'].filename
    data = form['file'].file.read()
    open(filename, "wb").write(data)
    self._set_headers()
    self.wfile.write(self._html("hi!"))
python html
2个回答
0
投票
  • 而不是为HTTP响应和路由编写自定义方法您可以使用烧瓶的引擎,轻巧的框架可以提供路由引擎以及该应用程序的所有功能和安全性,这还提供了管理所有类型的http请求所需的内容

https://www.palletsprojects.com/p/flask/


0
投票

使用urllibs下载文件。这是两个示例供您使用。

import urllib
urllib.urlretrieve ("http://www.yourdomain.org/myFile/myCV.pdf", "myCV.pdf")

import urllib2
myDownloadedFile = urllib2.urlopen("http://www.yourdomain.org/myFile/myCV.pdf")
with open('myCV.pdf','wb') as output:
    output.write(myDownloadedFile.read())

OP问题:

import httplib

def doesFileExist(domain, path):
     conn = httplib.HTTPConnection(site)
     conn.request('HEAD', path)
     response = conn.getresponse()
     conn.close()
     return response.status == 200

if(doesFileExist("http://www.yourdomain.org", "/myCV.pdf"):
     #run the code above
© www.soinside.com 2019 - 2024. All rights reserved.