BaseHTTPServer无法识别CSS文件

tpa*_*ott 2 python

我正在写一个非常基本的网络服务器(好吧,尝试),虽然它现在正在提供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):
            ...
Run Code Online (Sandbox Code Playgroud)

为了提供CSS文件,我需要做些什么特别的事情吗?

谢谢!

Joh*_*ooy 6

您可以将其添加到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
Run Code Online (Sandbox Code Playgroud)

另外

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)
Run Code Online (Sandbox Code Playgroud)