在mthon中使用HTTPServer混合mime类型

时间:2014-01-28 05:27:52

标签: python html css mime-types

现在我有了这个文件结构

server-
      |
      |css-
      |   |bad.css
      |
      |html-
      |    |bad.html
      |
      |jpg-
      |      |bad.jpg
      |
      |server.py

这是bad.css:

body
{
    background-image:url('bad.jpg');
    background-repeat:no-repeat;
    background-position:right top;
    margin-right:200px;
}

这是bad.html:

<html>
<head>
<link rel="stylesheet" type="text/css" href="bad.css">
</head>
<body>
    <h1>This isn't a thing!</h1>
    <p>You must be mistaken. But <a href="/index">here</a> is where you can find your way again.</p>
</body>
</html>

这是server.py

的相关部分
from BaseHTTPServer import BaseHTTPRequestHandler as Handler
from mime types import guess_type

class MyHandler(Handler):
    def do_GET(self):
        print self.path
        print self.headers
        extensions = ['html', 'css', 'jpg']
        fname = self.path
        for ext in extensions:
            if fname.endswith(ext):
                fname = ext + fname
                break
        if fname.split('/')[0] == '':
            fname = 'html/bad.html'
        mimetype = guess_type(fname)[0]
        print fname
        data = open(fname, 'rb')
            self.send_response(200)
        self.send_header('Content-type', mimetype)
        self.end_headers()
        self.wfile.write(data.read())
        data.close()

我的更新代码应该已修复它,但现在我的浏览器根本不渲染它,它只显示html代码。 Screen shot of what I am seeing

1 个答案:

答案 0 :(得分:0)

您的css和图像无法加载的原因是您的处理程序不知道如何处理这些文件的请求。这是一个简单的例子,在您链接的问题中从nosklo的答案中复制(并调整了abit)。

def do_GET(self):
    try:
        if self.path in ("", "/"):
            filepath = "html/bad.html"
        else:
            filepath = self.path.lstrip("/")

        f = open(os.path.join('.', filepath), "rb")

    except IOError:
        self.send_error(404,'File Not Found: %s ' % filepath)

    else:
        self.send_response(200)

        #this part handles the mimetypes for you.
        mimetype, _ = mimetypes.guess_type(filepath)
        self.send_header('Content-type', mimetype)
        self.end_headers()
        for s in f:
            self.wfile.write(s)

NB:您必须更改html中的css链接

<link rel="stylesheet" type="text/css" href="../css/bad.css">

<link rel="stylesheet" type="text/css" href="/css/bad.css">