Python BaseHTTPRequestHandler CSS已加载但未渲染

0 投票
1 回答
16 浏览
提问于 2025-04-12 05:35

我遇到麻烦了。下面的代码可以返回index.html和请求的css文件,但当我用Firefox打开index.html时,页面却没有应用css样式。我在Konqueror(也是基于Chrome的浏览器)中也遇到了同样的问题。

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        if (self.path.endswith("/")):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            with open('index.html', 'r') as file:
                template = file.read()
            self.wfile.write(bytes(eval_template(template, env).encode("utf-16")))
        
        elif (self.path.endswith(".css")):
            with open(os.path.join('.', self.path[1:]), 'rb') as file:
                response = file.read()
            self.send_response(200)
            self.send_header("Content-type", "text/css")
            self.end_headers()
            self.wfile.write(response)

在index.html中,css是这样引用的:

<link rel="stylesheet" type="text/css" href="style.css" />

当我查看开发者控制台时,可以确认对style.css文件的请求没有问题(显示200 OK)。

而当我直接用Firefox打开这个文件时,它能在同一个目录下找到css,并且正确地应用样式,所以我觉得我的代码可能缺少了什么。

谢谢大家的帮助。

1 个回答

0

在GetSet给我指明了方向之后,我发现把CSS的写法改成:

self.wfile.write(bytes(response))

就解决了这个问题。

撰写回答