A Simple Python CGI Server Tutorial -CGI Input/Output

GOTO Part 1

This article will deal with retrieving and using input to your CGI programs.  There are two ways to get input from your CGI programs, encoded within the URL and submitted through forms.  This tutorial will go over both methods.

We’ll need to do a little setup to begin, if you’ve already read through the first tutorial you should be very familiar with this process.

First we need to create a directory to house our CGI server and scripts, for this tutorial we’ll name it ‘server’.  Create a new file, with the following program, in the ‘server’ directory and name it ‘server.py’.

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]

httpd = server(server_address, handler)
httpd.serve_forever()

Give ‘server.py’ executable permissions ($ chmod +x server.py).  The next step is to create a page that will give us a link with an encoded URL.  To do this we’ll create a simple HTML page with nothing but the encoded link in it.  Create a new file named ‘link.py’ in the ‘server’ directory, with the following code and give it executable permissions ($ chmod +x link.py).

#!/usr/bin/env python

print """Content-type: text/html

<html><head><title>Test URL Encoding</title></head><body>
<a href="http://localhost:8000/test_urlencode.py?first=Jack&last=Trades">Link</a>
</body></html>'

Now we need to create the CGI script that will receive this data and output it into a new page.  Create a new file named ‘test_urlencode.py’ in the ‘server’ directory and input the following code.

#!/usr/bin/env python

import cgi

form = cgi.FieldStorage()

val1 = form.getvalue('first')
val2 = form.getvalue('last')

print """Content-type: text/html

<html><head><title>Test URL Encoding</title></head><body>
Hello my name is %s %s
</body></html>""" % (val1, val2)

Remember to give executable permissions to all your CGI scripts ($ chmod +x test_urlencode.py).  That’s it!  We now have a working CGI script.  To test it type the following into the location bar of your browser.

http://localhost:8000/link.py

Click on the link and the ‘test_urlencode.py’ script will output a page that says “Hello my name is Jack Trades”.  You can play around with the output by changing the URL of the link to whatever you want.  Below is a sample of URLs and their output, you can type/paste these directly into the location bar (no need to modify the ‘link.py’ script).

http://localhost:8000/test_urlencode.py?first=Jack&last=Trades
Hello my name is Jack Trades

http://localhost:8000/test_urlencode.py?first=Adam&last=Baum
Hello my name is Adam Baum

http://localhost:8000/test_urlencode.py?first=Anna&last=Grahm
Hello my name is Anna Grahm

Courtesy of Bart Simpson…
http://localhost:8000/test_urlencode.py?last=Tinkle&first=Ivana
Hello my name is Ivana Tinkle

OK, that’s enough fun for now.  Let’s move on to retrieving input from form data.  The first thing we must do is create a form to enter some data into.  We’ll do this by writing another CGI script to output the HTML form.  Create another file in the ‘server’ directory named ‘form.py’ with the code below.

#!/usr/bin/env python

print """Content-type: text/html

<form method="post" action="test_form.py">
<textarea name="comments" cols="40" rows="5">
Enter comments here...
</textarea>
<br/>
<input type="submit" value="Submit">
</form>"""

This is the form that will be presented to the user to allow them to enter their ‘comments’.  Remember to give this script executable permissions ($ chmod +x form.py).  Next create another file in the ‘server’ directory named ‘test_form.py’, this is the CGI script that will accept the form data and create a new page that includes the data.

#!/usr/bin/env python

import cgi

form = cgi.FieldStorage()

val1 = form.getvalue('comments')

print """Content-type: text/html

The form input is below...<br/>"""
print val1

Give this file executable permissions as well ($ chmod +x test_form.py) and then go back to your browser and enter the following line in the location bar.

http://localhost:8000/form.py

You should see a form with a single text area and a submit button.  Type whatever you want to in the text area, I chose “la de da de, we like to party”, and hit the submit button.  You should be presented by a page that says…

The form input is below…
la de da de, we like to party

Congratulations you have successfully handled form data with a CGI script.  You’ll notice that Python’s cgi module uses cgi.FieldStorage() to access both URL encoded input as well as form based input.  I neglected to go over the scripts line-by-line because there are very few concepts introduced in each of them.  If you have any questions, or would like me to clarify something, please leave a comment below.

Advertisements

8 thoughts on “A Simple Python CGI Server Tutorial -CGI Input/Output

  1. I like the short but sweet python cgi examples. I wrote a proof of concept web server/script that was self contained with no cgi handling. The xml data file automatically created or edited by the script is the only other file. You can check it out at http://launchpad.net/~danyellawson/pypad or by branching with bazaar.
    bzr branch lp:pypad

    • Thanks. Python makes it pretty easy to get something basic up and running. This particular web server was made to serve the Pointless Programming Reference before it was released to the world.

  2. Hi, I found this very helpful as a beginner, but how do I silence the output from the web server so that it does not report the server’s responses to the colsole ??

  3. There is a error in the link.py code. It needs to end with “”” instead of ‘

  4. Great guide, it is exactly what I needed ! It’s actually perfect as it will allow me to use html, which I know a bit, as basically a GUI for python script – without having to deal with any GUI problem, and with the css coming handy when it comes to displaying trees of data.

  5. I can’t get form.py bit to work properly, the page display is completely blank and following stack trace is produced on the terminal running the server.py script:

    1.0.0.127.in-addr.arpa – – [25/Jan/2013 22:01:13] “GET /form.py HTTP/1.1” 200 –
    Traceback (most recent call last):
    File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/CGIHTTPServer.py”, line 251, in run_cgi
    os.execve(scriptfile, args, env)
    OSError: [Errno 8] Exec format error
    1.0.0.127.in-addr.arpa – – [25/Jan/2013 22:01:13] CGI script exit status 0x7f00
    1.0.0.127.in-addr.arpa – – [25/Jan/2013 22:01:13] code 404, message No such CGI script (‘//favicon.ico’)
    1.0.0.127.in-addr.arpa – – [25/Jan/2013 22:01:13] “GET /favicon.ico HTTP/1.1” 404 –

    both files are executable. Including the code for reference:

    ######## form.py ###############
    # /usr/bin/env python

    print “””Content-type: text/html

    Enter text here..

    “””

    ######## test_form.py ###############

    # /usr/bin/env python

    import cgi

    form = cgi.FieldStorage()

    val1 = form.getvalue(“comments”)

    print “””Content-type: text/html

    The form input is below”””
    print val1
    ######################

    Everything else leading up to this worked fine, looked over everything closely and can’t spot the problem.. any pointers? Thanks!

    • looks like it partially cut off my form.py code reference, reposting:

      # /usr/bin/env python

      print “””Content-type: text/html

      Enter text here

      “””

Comments are closed.