1. Home
  2. Computing & Technology
  3. Python

Building a Simple Web Server in Python

From , former About.com Guide

9 of 10

Sending Data to the Client

Unless we want to create a single-action server, the next step is to read input from the file object. When we do that, we should be careful to strip that input of excess whitespace.

line = cfile.readline().strip()

The request will come in the form of an action, followed by a page, the protocol, and the version of the protocol being used. If one wants to serve a web page, one splits this input to retrieve the page requested and then reads that page into a variable which is then written to the socket file object. A function for reading a file into a dictionary can be found in the blog.

In order to make this tutorial a bit more illustrative of what one can do with the socket module, we will forego that part of the server and instead show how one can nuance the presentation of data. Enter the next several lines into the program.

cfile.write('HTTP/1.0 200 OK\n\n')
cfile.write('<html><head><title>Welcome %s!</title></head>' %(str(caddr)))
cfile.write('<body><h1>Follow the link...</h1>')
cfile.write('All the server needs to do is ')
cfile.write('to deliver the text to the socket. ')
cfile.write('It delivers the HTML code for a link, ')
cfile.write('and the web browser converts it. <br><br><br><br>')
cfile.write('<font size="7"><center> <a href="http://python.about.com/index.html">Click me!</a> </center></font>')
cfile.write('<br><br>The wording of your request was: "%s"' %(line))
cfile.write('</body></html>')

Explore Python
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Networking
  5. Python Web Server: Sending Data to the Client

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

All rights reserved.