module import in cgi scripts

Gerhard Häring gerhard at bigfoot.de
Wed Mar 13 08:11:03 EST 2002


Dag wrote:
> I'm trying to write a cgi script in python but I'm having a lot of
> problems importing modules.
> 
> I've simplified my script down to
> #!/usr/bin/python2.2
> import pg
> print "hello\n"

This won't work as a CGI script. You'll have to send the HTTP headers, 
then an empty line, then the HTTP body. For the HTTP headers, you'll 
need at least the content type, so use something like this:

print "Content-type: text/plain" # for plain text, or text/html for HTML
print
print "hello"

> if I run it from the command line it prints "hello" as expected,
> but if I put it in my cgi-bin directory and access it from a web
> browser the web server returns Internal Server Error and the 
> error log says:
> Traceback (most recent call last):
>   File "/var/www/cgi-bin/summarypie.py", line 4, in ?
>     import pg
> ImportError: No module named pg
> 
> I have checked and double checked and the pg modules is in the
> python sys.path.  What's wrong?

Most probably the CGI script is run as user nobody, group nogroup and 
the pg module or its parent directory don't have the correct 
permissions. Doing a "chmod -R +rX" on your Python library directory 
should fix this.

To test this kind of problem, you can also su to root, then su to nobody 
  to have the same environment a CGI script run under Apache.

Btw. you should also consider using pgdb instead of pg (assuming pg is 
part of PyGreSQL). pgdb is the DB-API 2.0 compliant wrapper on top of 
pg. If you use pgdb, you can easily switch from PyGreSQL to a different 
Python-PostgreSQL database interface later. Or to an altogether 
different database. The pg module, however, uses a proprietary interface.

If you use PyGreSQL, also be sure to use the latest version, as this 
contains fixes for some very annoying bugs. The most current can be 
found inside the PostgreSQL 7.2 source tarball.

Gerhard




More information about the Python-list mailing list