自定义简单的Python HTTP服务器不提供css文件

pra*_*vDa 6 css python http

我发现用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)
Run Code Online (Sandbox Code Playgroud)

它工作正常,除了事实 - 它不提供任何css文件(它没有css渲染).任何人都有这个怪癖的建议/解决方案?

最好的问候,praavDa

Ric*_*dle 9

您明确地将所有文件作为Content-type: text/html服务CSS文件的地方提供服务Content-type: text/css.有关详细信息,请参阅CSS-Discuss Wiki上的此页面.Web服务器通常有一个查找表,可以从文件扩展名映射到Content-Type.

  • 在python中,模块mimetypes具有查找表 (3认同)

nos*_*klo 6

它似乎返回所有文件的html mimetype:

self.send_header('Content-type', 'text/html')
Run Code Online (Sandbox Code Playgroud)

而且,它似乎非常糟糕.你为什么对这个糟糕的服务器感兴趣?查看cherrypy或paste以获得HTTP服务器的良好python实现和一个很好的代码来研究.


编辑:尝试为您修复它:

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)
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用这个sucky,因为它是我的项目的主题 - 我需要在python中编写http服务器.谢谢你的回复. (3认同)