我有一个使用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!"))
使用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