【问题标题】:How to serve any file type with Python's BaseHTTPRequestHandler如何使用 Python 的 BaseHTTPRequestHandler 处理任何文件类型
【发布时间】:2009-07-07 19:06:36
【问题描述】:

考虑以下示例:

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())

【问题讨论】:

  • 有人可以解释为什么调用 open() “可能使您计算机上的每个文件都可读”吗?在此示例中,您将如何针对提供文件的这种情况进行保护?
  • @brooksbp 我认为他的意思是用户可以键入一个路径,该路径将导航到您计算机上的另一个目录,例如向上一个或多个目录。但是使用上面的代码只能访问html文件。

标签: python httpserver


【解决方案1】:

将二进制作为参数传递给 open()。这个:

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

而不是这个:

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

UNIX 不区分二进制和文本,但 windows 可以。但如果脚本在 UNIX 上执行,“b”将被忽略,这样你就安全了。

【讨论】:

  • 在 Python 3 中,Python 在二进制文件和文本文件之间产生了差异,因此您不妨现在就将正确的标志放在那里。 :)
【解决方案2】:

您的线路可以正常工作。问题在于适当地设置Content-type。您需要将其设置为 application/zip 而不是 text/html

【讨论】:

  • 没错,但我已经这样做了。 JosefAssad 发现了我遇到的问题。但你是对的。
【解决方案3】:

如果你想共享任何类型文件夹中的文件,那么你也可以尝试输入命令

python -m SimpleHTTPServer

这将在端口 8000 启动服务器,您可以浏览文件(通过目录列表)

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2011-10-19
    相关资源
    最近更新 更多