Created
May 29, 2018 06:15
-
-
Save redraiment/fdb7451e0f3008c32bf6c42db8eafd3b to your computer and use it in GitHub Desktop.
提供简单的上传和下载功能的Python Web服务
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import BaseHTTPServer | |
import cgi | |
import mimetypes | |
import os | |
import posixpath | |
import shutil | |
if not mimetypes.inited: | |
mimetypes.init() | |
class RESTful(BaseHTTPServer.BaseHTTPRequestHandler): | |
exts = mimetypes.types_map.copy() | |
exts.update({'': 'application/octet-stream'}) | |
def mime_type(self, path): | |
base, ext = posixpath.splitext(path) | |
ext = ext.lower() | |
return self.exts[ext] if ext in self.exts else self.exts[''] | |
def not_found(self): | |
self.send_response(404) | |
self.end_headers() | |
def download(self, filename): | |
f = open(filename, 'rb') | |
fs = os.fstat(f.fileno()) | |
content_type = self.mime_type(filename) + "; charset=utf-8" | |
content_length = str(fs[6]) | |
last_modified = self.date_time_string(fs.st_mtime) | |
self.send_response(200) | |
self.send_header("Content-Type", content_type) | |
self.send_header("Content-Length", content_length) | |
self.send_header("Last-Modified", last_modified) | |
self.end_headers() | |
shutil.copyfileobj(f, self.wfile) | |
f.close() | |
def do_GET(self): | |
filename = self.path[1:] | |
if os.path.isfile(filename): | |
self.download(filename) | |
else: | |
self.not_found() | |
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 | |
f = open(filename, 'wb') | |
shutil.copyfileobj(form['file'].file, f) | |
f.close() | |
self.send_response(201) | |
self.send_header("Content-Length", "0") | |
self.end_headers() | |
if __name__ == '__main__': | |
httpd = BaseHTTPServer.HTTPServer(('', 8080), RESTful) | |
print ("http %s %s" % httpd.socket.getsockname()) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment