HOME
stuff you never thought you wanted to know.

 

 
Making a simple web server in Python

Making a simple web server in Python.

written by Jon Berg <jon.berg[at]turtlemeat.com>

The great thing about Python is what they call "batteries included", that means a lot of functionallity is bundled with the programming language. And the functionallity is fairly straight to use.

Today we are going to demonstrate how to build a web server in less than 30 min. using the classes from the Python library. We are also going to have some "advanced" functionallity in this server. We want to do dynamic content serving (ala what ASP or PHP do), and be able to take POST from forms. This may sound as a complex task, but as you will see every body can acomplish this through some high level programming interfaces. You don't have to know much about the HTTP protocol at all. Except some basic that when the client request something it is a "GET", and when the client sends something it is in our case a POST. Some basic responce codes like 200 is OK for GET, and 404 is file not found, 301 is OK for a Post.

The web server is implemented as an extention of the BaseHTTPRequestHandler. This means that we define a class an implemenet some methods that will be called when the web server gets requests. There are two methods one for GET requests and one for POST requests.

Lets look at the code:


The main() tries to start the server at port 80 with a reference to the class we just implemented. To quit the server you can press ctrl-c. And the server will close the socket and quit.

The do_GET() gets invoked when you do a GET request. It do checking to see what type of file is requested. If it is a html file it tries to open it and send it to the client. If it is a esp file, our dynamic content, it will print out the current day and year.

The do_POST() gets invoked when you do a POST request. It then displays the content that is uploaded. The name of the formelement is hardcoded to be "upfile".

Running the example:
start the webserver with python webserver.py
Then you can open your web browser and type in http://localhost/index.html or http://localhost/index.esp
To test the upload, you open the upload.html, press browse, open a small text file, click "press", the server will echo back the file.

Download the example code. (webserver.py, index.html, upload.html)

Update: Oct 2011. There was some confusion about how the POST is handled in this example. That it sends code 301.

> I have one question. When you respond to the POST message, you send a
> 301 response, followed by the html page generated. This works using
> Firefox on Linux, but MSW IE6 gives a 'Page cannot be displayed' error.
>
> If I change it to sending a 200 response, followed by a content-type
> header, followed by the html page, it works correctly on both platforms.
>
> According to what I have read, 301 is actually a redirection response.
> Can you explain how this is supposed to work, and why it does not work on IE6.
You are correct that it is a redirect response.

I think the script is a bit incomplete in this respect. Normally when
you want to redirect a POST request it can be done by sending a
redirect response, but it also requires the "Location:" header to
work. I think this is what happens and maybe confusing to IE, but
luckily Firefox is better at guessing what to do and just displays the
content and gives up, right?
It also seems to be more correct to return 302 or 304, when
redirecting a POST request.
There is also this design pattern to redirect after a POST that can be
useful:
http://en.wikipedia.org/wiki/Post/Redirect/Get

Other that that if you don't want the redirecting stuff, the correct
thing would then be to just return a 200 response code. And the
content returned will be displayed in the browser.


Pointers to related stuff on the hypertext transfer protocol (http) and web servers:

Making a simple web server in Java. (a bit lower level) This is a tutorial I did on how to do somewhat the same but in Java. This implementation is much more bottom up, with sockets and not that many short cuts as you can do in Python.

HowStuffWorks This is a very basic introduction for the novice on how web servers works. Has also other text about Internet and Routers, in easy to understandable language. Nice if you are starting out learning.

HTTP Made Really Easy Here is some nice text that goes through the main points in HTTP. A little more technical. It's recommended that you know these things to understand the above tutorial.

Apache the best and most widely used web server on the Internet today, check it out. If you want to run your own web server this is the one to get, you can get binaries for both Windows and Unix. You can download the entire sourcecode if you want to check how it was made.

Mozilla / Netscape is a nice web browser. Get rid of the Explorer.

RFC-1945 RFC describing Hypertext Transfer Protocol -- HTTP/1.0

RFC-2616 RFC describing Hypertext Transfer Protocol -- HTTP/1.1

RFC webpage The Request For Comment webpage, RFC are technical documents describing all sorts of protocols on the Internet.

Python webpage Download Python for windows or linux.



Linux
Setup Software Raid 1 with LVM
Setup Linux with Desktop

Google
Manage your website ads with DFP
Google AdSense for Domains - not so great
Let Google Handle Email for your Domain Name
Page Rank banned by Google
Google's highest ranked web pages
SEO intelligent spam causes irrelevant search results
Google Sandbox
Google ranking factors
How to not give out page rank in web page links

Amazon
Amazon Cloudfront versus Shared Hosting

Web Server Programming
Simple Java web server
Simple Python web server
Configuring Apache webserver with .htaccess file

Windows
Turn off the loginscreen in XP, after installing .NET .

Turn off xp login screen unread mail count
What is .NET

Web (webmastering)
Introduction to Cascading style sheets (CSS)
The value of Alexa traffic rank
HTML META tag, not a search engine optimization tool
Create a maintainable webpage with modularization
The www prefix in your domain name
What is RSS and cool things RSS can be used for
MySql backup and restore with phpMyAdmin

Mix Computer related text
Doing business (making money) with Information Technology
Business with Computer Science
Research in Computer Science
Current and future possibilities of Medical Informatics
Tasks that make sense to have automated
Programming handheld mobile devices (overview)
Security tips for the web surfer
Price and Capacity in computer hardware
Java RMI Tutorial.

Microsoft Word
Page numbering in Word
Numbering headers or outlines in Word
Create a List of Figures
Turn off the default collapsing menus in Word




Turtlmeat.com 2004-2011 ©