[mod_python] Why this code fails?

Graham Dumpleton grahamd at dscpl.com.au
Sun Nov 19 22:20:51 EST 2006

=?iso-8859-1?Q?Luis_M._Gonz=E1lez?= wrote ..
> Hello all,
> I have this script, which works fine when tested with the interpreter,
> but fails when used with mod_python:
> # index.py
> import sys, os
> sys.path.append(os.getcwd() + '/templates')
> sys.path.append(os.getcwd() + '/models')

You shouldn't modify sys.path from inside a handler code file as it can
cause lots of problems. Also, os.getcwd() is going to usually return '/'
and not the directory the file resides in. It is also not a good idea to be
placing modules required by your handlers within the document tree
like this because if you do not protect them properly from access in
the Apache configuration, users may be able to trigger code or access
data within the modules directly.

The better thing to do is to move those module directories somewhere
outside of the document tree and then use the PythonPath directive to
extend the value of sys.path with the directory you place the two module
directories in. 

Also note there are various problems with the module importer in
current versions of mod_python. See:


This could be resulting in you picking up a wrong version of a module
if the same module name is used in multiple places, or an old module
version cached in memory and not changes you may have made on disk
since it was loaded. You may as a result have to restart Apache if not
getting latest module changes. You may also need to use PythonInterpreter
to make sure distinct applications operate in their own interpreters to
avoid problems with similar module names being used.


> from models import *
> result = Customers.select()
> def index(req):
>     req.content_type = 'text/html'
>     for i in result:
>         req.write(i.Company + '<br>')
> Explanation:
> I have a main directory and two subdirectories: templates and models.
> Inside the models folder I have a module called "models.py", where I
> imported an ORM and defined the db connection and models (included
> "Customers").
> Although it works perfectly as a standalone app, it doesn't work with
> mod_python.
> The error message I get is:
>              NameError: name 'Clientes' is not defined
> I guess it has to do with the way mod_python handles the import of
> modules, or perhaps with the way I modify the sys.path... but I can't
> figure out the solution.
> Any hint would be highly appreciated...
> Thanks!
> Luis

More information about the Mod_python mailing list