BaseHTTPServer无法识别CSS文件

2024-04-24 00:43:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个非常基本的web服务器(嗯,正在尝试),虽然它现在可以很好地服务于HTML,但我的CSS文件似乎根本无法识别。我的机器上也运行着Apache2,当我把我的文件复制到docroot时,页面的服务就正确了。我还检查了权限,它们似乎没问题。以下是我目前掌握的代码:

class MyHandler(BaseHTTPRequestHandler):
     def do_GET(self):
           try:
                if self.path == "/":
                     self.path = "/index.html"
                if self.path == "favico.ico":
                     return
                if self.path.endswith(".html"):
                     f = open(curdir+sep+self.path)
                     self.send_response(200)
                     self.send_header('Content-type', 'text/html')
                     self.end_headers()
                     self.wfile.write(f.read())
                     f.close()
                     return
                return
            except IOError:
                self.send_error(404)
      def do_POST(self):
            ...

为了提供CSS文件,我需要做些什么吗?在

谢谢!在


Tags: 文件pathself服务器机器sendwebreturn
2条回答

您需要添加一个处理css文件的案例。尝试更改:

if self.path.endswith(".html") or self.path.endswith(".css"):

你可以把这个加到if子句中

            elif self.path.endswith(".css"):
                 f = open(curdir+sep+self.path)
                 self.send_response(200)
                 self.send_header('Content-type', 'text/css')
                 self.end_headers()
                 self.wfile.write(f.read())
                 f.close()
                 return

或者

^{pr2}$

相关问题 更多 >