Python BaseHTTPServer无法识别CSS文件
我正在编写一个非常基本的Web服务器(嗯,正在尝试),虽然它现在可以很好地提供HTML,但我的CSS文件似乎根本无法识别。我的机器上也运行着Apache2,当我将文件复制到docroot时,页面被正确送达。我还检查了权限,它们似乎没有问题。以下是我目前掌握的代码:Python BaseHTTPServer无法识别CSS文件,python,Python,我正在编写一个非常基本的Web服务器(嗯,正在尝试),虽然它现在可以很好地提供HTML,但我的CSS文件似乎根本无法识别。我的机器上也运行着Apache2,当我将文件复制到docroot时,页面被正确送达。我还检查了权限,它们似乎没有问题。以下是我目前掌握的代码: class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path == "/":
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文件,我需要做什么特别的事情吗
谢谢 您需要添加一个处理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
或者
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)
嗯,您可能希望将其作为一个单独的案例添加—您希望为CSS设置不同的内容类型。但这应该让你开始。谢谢你的回复。我最后加了一个单独的箱子,效果很好。谢谢!我想是这样的,但不确定我是否需要一个单独的箱子。加上这个,它就像一个魅力!这对我来说是非常有启发性的代码——谢谢,格尼布勒。一个小提示:至少在Python2.7中,它是mimetypes.types\u映射(复数),而不是.type\u映射