Writing CGI Scripts in Python

 in
This article is neither a Python tutorial nor a CGI tutorial, but a “Python Presentation from a CGI perspective”.
Database Queries

Now we are going to look at more “real life” scripts that could be used in an Intranet application.

We are going to use PostGres95. It must be installed and configured properly. I won't explain that process here, since it would require a lot of additional text. But two things should be mentioned:

  1. The “user” which is used when a CGI script is run on your system must have access to PostGres95, and to the database being queried.

  2. The connect() function used in the following scripts may need to be adapted to work on your system. Mine doesn't need any parameters, since everything works with the default settings I've configured.

See the PostGres95 manual for more information.

The PyGres95 modules offer the same interface as the LIBPQ API, which is also described in the PostGres95 manual. You should know that there is a connect() function used to connect to the database, and a query() function that receives an SQL string as a parameter.

Listing 8 shows a script that will handle queries on a customer database which has a structure similar to what the fields might be in a query form. The script will connect to the database, build an SQL command, query the database, and finally, display the results in a table that is built on the fly for each request. Of course the SQL statements here are very simple, but scripts could be written to do anything.

This script is not very practical. We'd have to write specific code for every table we want to use. The script of Listing 9 implements a general query on any single PostGres95 table/view from an HTML form. This means that it will work for any query where you need a subset of a table. It could work for customers (as in our example), providers or articles. The main difference from the former script is the build_query() function:

The script now implements the following behaviour: a query made on a numeric field will require an exact match, while a query made on a text field will be considered as ending with a wildcard. This means that numeric fields are considered to be IDs, and that it's not possible, for example, to use it to search articles with a value between $500 and $1,000. But it can be used to search a personal database for all names beginning with “Van”.

Restriction: to determine the type of a field, we'll consider it numeric if its name ends in “num”. This is because all data sent to a CGI script is seen as text. Of course, you could parse the value to see if it's numeric or not. But it's not always a good choice. If you want to search for all telephone numbers beginning with “800”, our script will look for an exact match if it thinks it's a numeric field, and it will find nothing. Of course, you can also completely rewrite the build_query() function to fit your needs.

The script needs to know on which table it should perform the query. That's why our form contains an invisible field called TableName. It must be set to the name of the desired table.

The form field names must be the same as the table field names, because the script uses them to perform the query. But, of course, the labels displayed on the user input form can be anything.

And finally, the script contains several lines that can be commented or uncommented to enable or disable some debug strings in the resulting page (e.g., as the query string).

Where to Go from Here?

There are several powerful features of Python that weren't discussed in this article. Python supports exception handling, as in C++ or Modula-3. This can be useful to trap errors in CGI scripting. It's even possible to write a script with a function to send a bug report by e-mail to its author when it detects an unexpected error. And of course, you can write your own classes.

For CGI scripting, although we didn't use them in our sample scripts, some additional features are available. On the Python home page, you'll find code to embed the Python interpreter in Apache. And Apache itself comes with optional modules that interact with PostGres95. But PostGres95 is not the only database available—among others, there is a module for Oracle.

Now, if you want to try Python, the first thing to do is read the Python Tutorial (see Documentation and Availability), then print a copy of the Python Library Reference manual. Then, you should try to reach simple goals—like deleting all ~*.tmp files older than one day, for example.

Finding Python on the Web
  1. http://www.python.org/

  2. http://www.ora.com/

  3. http://www.python.org/python/arwbook.html

  4. news:comp.lang.python

  5. http://www.ki.net/postgres95/

  6. http://zen.via.ecp.fr/via_dvpt/products/pygres.html

Michel Vanakan is a 32-year-old software engineer and part-time network administrator. His interests include fantasy and Sci Fi books and games, walks in the wilderness and flights with light aircraft. He can be reached at Michel.Vanaken@ping.be.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thanks for tutorial! I found a syntax error.

Anonymous's picture

Thanks for the tutorial. :)

There is a syntax error in listing 7, in the line "if len( fields ) = 0 :". You probably see it now, it should have been "==" and not "=" - we need the comparison operator, not the assignment operator.

-Nobody

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix