简体   繁体   中英

Mixing mime types with HTTPServer in python

Right now I have this file structure

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

this is bad.css:

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

this is 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>

this is the relevant part of 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()

My updated code should have fixed it, but now my browser doesn't render it at all, it just shows html code. 我所看到的屏幕截图

The reason why your css and images won't load is because your handler doesn't know how to handle the request(s) for those files. Here is a simple example copied (and tweaked abit) from nosklo's answer in the question you linked to.

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: You will have to change the css link in your html from

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM