如何用Python的BaseHTTPRequestHandler服务任意文件类型

12 投票
3 回答
29000 浏览
提问于 2025-04-15 12:44

考虑以下示例:

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        try:
            if self.path.endswith(".html"):
                f = open(curdir + sep + self.path) #self.path has /test.html
#note that this potentially makes every file on your computer readable by the internet

                self.send_response(200)
                self.send_header('Content-type',    'text/html')
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
                return

        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)


def main():
    try:
        server = HTTPServer(('', 80), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

如果我还想提供一个ZIP文件...我该怎么做呢? 我觉得这一行可能不太对吧?

self.wfile.write(f.read())

3 个回答

3

如果你想分享一个文件夹里的文件,不管是什么类型的文件,你可以试着输入这个命令

python -m SimpleHTTPServer

这个命令会在8000端口启动一个服务器,你就可以通过目录列表来浏览这些文件了。

4

你的代码是没问题的。问题在于要正确设置 Content-type。你应该把它设置为 application/zip,而不是 text/html

10

把二进制数据作为参数传给open()函数。这样:

f = open(curdir + sep + self.path, 'rb')

而不是这样:

f = open(curdir + sep + self.path)

在UNIX系统中,二进制和文本没有区别,但在Windows系统中是有区别的。不过如果你的脚本在UNIX上运行,"b"这个参数会被忽略,所以你可以放心。

撰写回答