BaseHTTPServer无法识别CSS文件
我正在写一个比较基础的网页服务器(其实是在尝试),现在它可以很好地提供HTML文件,但我的CSS文件似乎根本没有被识别。我机器上也运行着Apache2,当我把文件复制到文档根目录时,页面可以正常显示。我也检查了权限,似乎没有问题。以下是我目前的代码:
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文件吗?
谢谢!
2 个回答
0
你需要添加一个处理 CSS 文件的情况。试着修改一下:
if self.path.endswith(".html") or self.path.endswith(".css"):
7
你可以把这个加到你的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)