自定义简单Python HTTP服务器无法提供CSS文件

8 投票
3 回答
11661 浏览
提问于 2025-04-15 12:01

我找到了一段用Python写的非常简单的HTTP服务器,它的do_get方法看起来是这样的:

def do_GET(self):
        try:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers();
            filepath = self.path
            print filepath, USTAW['rootwww']

            f = file("./www" + filepath)
            s = f.readline();
            while s != "":
                self.wfile.write(s);
                s = f.readline();
            return

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

这个服务器运行得还不错,只是有个问题——它不能提供任何CSS文件(也就是说,页面没有样式,看起来很简单)。有没有人能给点建议或者解决这个问题的方法?

最好的祝福,
praavDa

3 个回答

2

可以查看标准库中的 SimpleHTTPServer.py,这是一个更安全、更合理的实现,如果需要的话,你可以根据自己的需求进行定制。

10

你现在把所有文件都当成 Content-type: text/html 来处理,但其实你应该把CSS文件当成 Content-type: text/css 来处理。想了解更多,可以看看 这个CSS讨论的页面。一般来说,网络服务器会有一个查找表,用来把文件的后缀名和对应的内容类型联系起来。

6

看起来这个服务器对所有文件都返回了HTML的类型:

self.send_header('Content-type', 'text/html')

而且,这样的情况似乎很糟糕。你为什么对这个不怎么样的服务器感兴趣呢?可以看看cherrypy或者paste,它们是不错的Python HTTP服务器实现,代码也很好学习。


编辑:我在试着帮你修复这个问题:

import os
import mimetypes

#...

    def do_GET(self):
        try:

            filepath = self.path
            print filepath, USTAW['rootwww']

            f = open(os.path.join('.', 'www', filepath))

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

        else:
            self.send_response(200)
            mimetype, _ = mimetypes.guess_type(filepath)
            self.send_header('Content-type', mimetype)
            self.end_headers()
            for s in f:
                self.wfile.write(s)

撰写回答