Custom Python simple HTTP server not serving css files

I found written in python, a very simple http server, the do_get method looks like this:

def do_GET(self):
        try:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers();
            filepath = self.path
            print filepath, USTAW['rootwww']

            f = file("./www" + filepath)
            s = f.readline();
            while s != "":
                self.wfile.write(s);
                s = f.readline();
            return

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

It works fine, except that it does not serve any css files (it is displayed without css). Has anyone got a suggestion / solution for this quirk?

Regards, praavDa

+5
source share
3 answers

seems to return html mimetype for all files:

self.send_header('Content-type', 'text/html')

Also, it looks pretty bad. Why are you interested in this sucking server? Look at cherrypy or paste for good Python implementations of the HTTP server and good code to learn.


EDIT : try to fix it for you:

import os
import mimetypes

#...

    def do_GET(self):
        try:

            filepath = self.path
            print filepath, USTAW['rootwww']

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

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

        else:
            self.send_response(200)
            mimetype, _ = mimetypes.guess_type(filepath)
            self.send_header('Content-type', mimetype)
            self.end_headers()
            for s in f:
                self.wfile.write(s)
+6

Content-type: text/html, CSS Content-type: text/css. . CSS- Wiki. - Content-Type.

+9

See the SimpleHTTPServer.pystandard library for a safer and more reliable implementation, which you can customize if you need.

+2
source

All Articles