首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BaseHTTPServer无法识别CSS文件

BaseHTTPServer无法识别CSS文件
EN

Stack Overflow用户
提问于 2010-07-20 22:41:39
回答 2查看 2.9K关注 0票数 3

我正在编写一个非常基本的well服务器(嗯,正在尝试),虽然它现在可以很好地为HTML提供服务,但我的CSS文件似乎根本无法识别。我的机器上也运行着Apache2,当我将我的文件复制到文档根目录时,页面可以正确地提供服务。我还检查了权限,它们看起来都很好。以下是我到目前为止拥有的代码:

代码语言:javascript
复制
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文件,我需要做什么特殊的事情吗?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-07-20 22:50:21

您可以将此代码添加到if子句中

代码语言:javascript
复制
            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

另一个选择

代码语言:javascript
复制
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)
票数 7
EN

Stack Overflow用户

发布于 2010-07-20 22:46:17

您需要添加一个处理css文件的案例。尝试更改:

代码语言:javascript
复制
if self.path.endswith(".html") or self.path.endswith(".css"):
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3291120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档