开发者

BaseHTTPServer not recognizing CSS files

I'm writing a pretty basic webserver (well, trying) and while it's now serving HTML fine, my CSS files don't seem to be recognized at all. I have Apache2 running on my machine as well, and when I copy my files to the docroot, the pages are served correctly. I've also checked permissions and they seems to be fine. Here's the code I have so far:

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):
            ...

Is there anything special I need to be doing in order to serve CSS files?

Thanks!


You could add this to your if clause

            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

Alternatively

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)


You need to add a case that handles css files. Try changing:

if self.path.endswith(".html") or self.path.endswith(".css"):
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜