gpt4 book ai didi

python - BaseHTTPServer 无法识别 CSS 文件

转载 作者:行者123 更新时间:2023-11-28 21:30:15 28 4
gpt4 key购买 nike

我正在编写一个非常基本的网络服务器(好吧,正在尝试),虽然它现在可以很好地提供 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 文件,我需要做什么特别的事情吗?

谢谢!

最佳答案

您可以将其添加到您的 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

或者

import os
from mimetypes import types_map
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == "/":
self.path = "/index.html"
if self.path == "favico.ico":
return
fname,ext = os.path.splitext(self.path)
if ext in (".html", ".css"):
with open(os.path.join(curdir,self.path)) as f:
self.send_response(200)
self.send_header('Content-type', types_map[ext])
self.end_headers()
self.wfile.write(f.read())
return
except IOError:
self.send_error(404)

关于python - BaseHTTPServer 无法识别 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3291120/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com