Python server showing html as text rather than rendering it

Viewed 68

I'm trying to make a server the long way for more control/ learning. when i try to make a simple one with bash i get mimetype errors.

I must be looking at this the wrong way but my server seems to make the browser render the html as text. the html i get in the browser is weird too.

any help would be mush appreciated!

server.py

from http.server import HTTPServer,BaseHTTPRequestHandler

HOST = "localhost"
PORT = 7800

class FeedSpeedServer(BaseHTTPRequestHandler):

    def do_GET(self):


        if self.path == "/":
            self.path = 'index.html'
        
        try:
            
            self.send_header("content-type", "text/html")
            self.send_header("content-type", "text/javascript")
            self.send_header("content-type", "text/css")
            self.end_headers()
            self.file = open(self.path).read()
            self.wfile.write(self.file.encode())
            self.send_response(200)
            
        except:
            self.file = "file not found"
            self.send_response(404)


httpd = HTTPServer((HOST, PORT), FeedSpeedServer)
print("server running...")
httpd.serve_forever()
print("server Stopped")

My web browser shows this...

screenshot

2 Answers

I have never worked with http.server for Python, but common examples I see send the status code first, then the headers, then the content.

Also, the Content-Type must be a single value. This worked for me:

    def do_GET(self):
        if self.path == "/":
            self.path = 'index.html'
        try:
            self.send_response(200)
            self.send_header("content-type", "text/html")
            self.end_headers()
            self.file = open(self.path).read()
            self.wfile.write(self.file.encode())
        except:
            self.send_response(404)
            self.file = "file not found"

If you plan to serve css/javascript, you might want to check the file extension of self.path and set self.send_header("content-type", "text/xxx") accordingly. An example:

    extensions = {
        "html": "text/html",
        "css": "text/css",
        "js": "text/javascript",
        "plain": "text/plain"
    }

    def set_content_type(self):
        extension = self.path.split(".")[-1]
        if extension in self.extensions:
            return self.extensions[extension]

        return self.extensions["plain"]

and replace self.send_header("content-type", "text/html") with self.set_content_type()

Related