Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom simple Python HTTP server not serving css files

Tags:

python

http

css

I had found written in python, a very simple http server, it's 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 ok, besides the fact - that it is not serving any css files ( it is rendered without css). Anyone got a suggestion / solution for this quirk?

Best regards, praavDa

like image 367
praavDa Avatar asked Jun 03 '09 21:06

praavDa


People also ask

How do you integrate CSS in Python?

CSS learning checklistCreate a simple HTML file with basic elements in it. Use the python -m SimpleHTTPServer command to serve it up. Create a <style></style> element within the <head> section in the HTML markup. Play with CSS within that style element to change the look and feel of the page.

Is CSS compatible with Python?

If you're interested in web development with Python, then knowing HTML and CSS will help you understand web frameworks like Django and Flask better. But even if you're just getting started with Python, HTML and CSS can enable you to create small websites to impress your friends.


2 Answers

You're explicitly serving all files as Content-type: text/html, where you need to serve CSS files as Content-type: text/css. See this page on the CSS-Discuss Wiki for details. Web servers usually have a lookup table to map from file extension to Content-Type.

like image 170
RichieHindle Avatar answered Sep 28 '22 01:09

RichieHindle


it seems to be returning the html mimetype for all files:

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

Also, it seems to be pretty bad. Why are you interested in this sucky server? Look at cherrypy or paste for good python implementations of HTTP server and a good code to study.


EDIT: Trying 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)
like image 26
nosklo Avatar answered Sep 28 '22 00:09

nosklo