如何使用Python的serve()函数来实现文件上传和下载功能
Python的http.server模块中的SimpleHTTPRequestHandler类提供了一个内置的文件服务器,可以用于实现文件上传和下载功能。SimpleHTTPRequestHandler类中有一个名为do_POST()的方法,可以用于处理POST请求,从而实现文件上传功能。同时,do_GET()方法可以用于处理GET请求,实现文件下载功能。
下面是使用http.server模块实现文件上传和下载的例子:
文件上传例子:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
class UploadHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
filename = self.headers['filename']
file_path = os.path.join(os.getcwd(), filename)
with open(file_path, 'wb') as file:
file.write(self.rfile.read(content_length))
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'File uploaded successfully.')
def run(server_class=HTTPServer, handler_class=UploadHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting file upload server...')
httpd.serve_forever()
if __name__ == '__main__':
run()
在上述例子中,首先定义了一个名为UploadHandler的类,继承自BaseHTTPRequestHandler类,并重写了do_POST()方法。在do_POST()方法中,首先获取请求头中的Content-Length和filename字段,分别表示文件的大小和文件名。然后根据文件名构造文件路径,并以二进制写的模式打开文件并写入请求体中的内容。最后返回一个上传成功的响应。
然后定义了一个run()函数,用于启动文件上传服务器。创建一个HTTPServer实例,并将UploadHandler类作为处理器。最后调用serve_forever()方法来启动服务器并持续监听请求。
文件下载例子:
from http.server import SimpleHTTPRequestHandler, HTTPServer
class DownloadHandler(SimpleHTTPRequestHandler):
def do_GET(self):
path = self.translate_path(self.path)
try:
f = open(path, 'rb')
self.send_response(200)
self.send_header('Content-type', 'application/octet-stream')
self.send_header('Content-Disposition', 'attachment; filename="%s"' % path.split('/')[-1])
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def run(server_class=HTTPServer, handler_class=DownloadHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting file download server...')
httpd.serve_forever()
if __name__ == '__main__':
run()
在上述例子中,首先定义了一个名为DownloadHandler的类,继承自SimpleHTTPRequestHandler类,并重写了do_GET()方法。在do_GET()方法中,首先打开请求的文件并读取其内容,然后发送响应头,指定响应内容的类型为application/octet-stream,表示是一个二进制文件。通过Content-Disposition字段设置响应头,指定下载文件的名称。最后将文件内容写入响应体中返回给客户端。
然后定义了一个run()函数,用于启动文件下载服务器。创建一个HTTPServer实例,并将DownloadHandler类作为处理器。最后调用serve_forever()方法来启动服务器并持续监听请求。
以上就是使用Python的http.server模块实现文件上传和下载功能的例子。通过使用do_POST()方法处理POST请求,实现文件上传;使用do_GET()方法处理GET请求,实现文件下载。可以根据实际需求对例子进行适当的修改和扩展。
