【问题标题】:Custom simple Python HTTP server not serving css files自定义简单 Python HTTP 服务器不提供 css 文件
【发布时间】:2009-06-03 21:31:32
【问题描述】:

我发现用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 文件(它在没有 css 的情况下呈现)。有人对此怪癖有建议/解决方案吗?

最好的问候, 正宗

【问题讨论】:

  • 快速建议:谷歌cherrypy。
  • 警告旧线程尝试将 .css 文件存储在 html 文件所在的同一目录中。

标签: python css http


【解决方案1】:

您明确将所有文件作为Content-type: text/html 提供,您需要将CSS 文件作为Content-type: text/css 提供。有关详细信息,请参阅this page on the CSS-Discuss Wiki。 Web 服务器通常有一个查找表来从文件扩展名映射到 Content-Type。

【讨论】:

  • 在 python 中,模块 mimetypes 有查找表
【解决方案2】:

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

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

而且,它似乎很糟糕。你为什么对这个糟糕的服务器感兴趣?查看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)

【讨论】:

  • 我正在使用这个很糟糕的,因为它是我项目的主题——我需要用python编写http服务器。感谢您的回复。
【解决方案3】:

请参阅标准库中的 SimpleHTTPServer.py 以获得更安全、更健全的实现,您可以根据需要对其进行自定义。

【讨论】:

  • 感谢您提供此链接 - 我现在对如何编写自己的代码有了更多了解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多