Database backed web applications: code walk through

The code proper is very simple. The script file starts with a one-line description of the program, a line of python code to get the database connection, then a collection of HTML fragments for printing the various pages that the application can generate, placed near the top for ease of configuration. Then there's the definition of the handler class that actually handles the request, and finally a standard Python idiom for instantiating an instance of the handler class and invoking a method to get the results.

The handler class is straightforward. The initialization method __init__ creates an instance of the standard Python library CGI handler class, initialize some instance attributes, and then copies the database connection and HTML fragments to instance variables so they can be changed in subclasses. After the handler is instantiated, the run method is invoked to control the work the object does, in an environment that traps errors so they can be handled reasonably.

The run method either calls an attribute based on the URL path, or displays the standard page for the hotlist, sorted according to the type found in the query by the method get_type. The only PATH-based method in this class is do_goto, that expects to find the id number of a hotlist item as an argument, updates the database for that item having been selected, and then redirects the browser to the URL for that item.

The display_page method is invoked to display the page. It uses the get_list method to get the current hotlist table, then the display_list method maps the display_item method over that list to format each item. Finally, display_page formats that list, along with various other handler object attributes, using the formatting strings saved in the __init__ method when the object was created.

Note that, as described in the section on software selection, all the code here does is parse out the HTTP request, figure out the SQL request to make based on that, then reformats the results for display. Or, if this is someone following a link, it updates the SQL database, then return an HTTP fragment to redirect the browser to the real URL.

Installing this script involves copying it to /usr/local/www/cgi-bin, and making sure that it's executable there. You should then be able use your browser to load the page /cgi-bin/hotlist.py from your FreeBSD server.

That's the first half of the application. The second half is the list checker.


Prev, Next, Contents

Mike Meyer,
March, 1999