Python

  1. Home
  2. Computing & Technology
  3. Python

Building a Simple Web Server in Python

From Al Lukaszewski, for About.com

10 of 10

Final Analysis and Shutting Down

If one is sending a web page, the first line is a nice way of introducing the data to a web browser. If it is left out, most web browsers will default to rendering HTML. However, if one includes it, the 'OK' must be followed by two new line characters. These are used to distinguish the protocol information from the page content.

The syntax of the first line, as you can probably surmise, is protocol, protocol version, message number, and status. If you have ever gone to a web page that has moved, you have probably received a 404 error. The 200 message here is simply the affirmative message.

The rest of the output is simply a web page broken up over several lines. You will note that the server can be programmed to use user data in the output. The final line reflects the web request as it was received by the server.

Finally, as the closing acts of the request, we need to close the file object and the server socket.

cfile.close()
csock.close()
Now save this program under a recognisable name. After you call it with 'python program_name.py', if you programmed a message to confirm the service as running, this should print to the screen. The terminal will then seem to pause. All is as it should be. Open your web browser and go to localhost:8080. You should then see the output of the write commands we gave. Please note that, for the sake of space, I did not implement error handling in this program. However, any program released into the 'wild' should. See "Error Handling in Python" for more.

Explore Python

About.com Special Features

Python

  1. Home
  2. Computing & Technology
  3. Python
  4. Networking
  5. Python Web Server: Final Analysis and Shutting Down

©2009 About.com, a part of The New York Times Company.

All rights reserved.