[mod_python] importing from a PSP file

Graham Dumpleton grahamd at dscpl.com.au
Thu Jan 6 04:08:29 EST 2005


On 06/01/2005, at 5:30 PM, Simon Wittber wrote:

> We've just started using mod-python PSP, so please excuse my ignorance.
>
> I found that I cannot import modules which exist in the same folder as
> the psp file being served by apache.
>
> eg:
> The file:
>
> /home/simon/public_html/test.psp
>
> cannot import:
>
> /home/simon/public_html/package/module.py
>
> unless the path '/home/simon/public_html' is sys.path.appended at the
> top of the psp page.
>
> To get around this problem, I added the following lines:
>
> cwd = str(os.path.split(self.filename)[0])
> sys.path.append(cwd)

You would need to be very careful with doing this as every request
against that resource would extend sys.path. You should at least
check it isn't in sys.path already. Extending sys.path can also
be problematic in a threaded environment as would exist in Apache
on Windows and if worker MPM is used on UNIX.

BTW, why the str() conversion? It should already be a string unless
there is something I am missing about Unicode strings.

> under line 207 in '/usr/lib/python2.3/site-packages/mod_python/psp.py'
> which cleared up the problem.
>
> Has anyone else come up against this problem? Does another (better)
> solution already exist somewhere else in mod-python?

Both the standard Python "import" directive and the mod_python
import_module() method use the "imp" module which will only look
for modules in sys.path. Thus the problem as you understand it.
Another problem with this, especially if you put your directory
last is that it may pick up a module of the same name from a
place elsewhere on the search path before it even gets to your
directory. Ie., not your module, but something else. This is a
source of various problems in mod_python.

If you want to look at other alternatives, you might look at the
module loading and caching system in the Vampire extension
package for mod_python. In Vampire things work a bit differently
and you must actually specify the specific directory that the
module of interest is in. Ie., sys.path is ignored. This is done
specifically to avoid the problems of having to set sys.path and
of potentially finding the wrong module.

Thus your code would be written as:

   import vampire

   directory = os.path.join(os.path.split(self.filename)[0],"package")
   module = vampire.importModule(directory,"module")

   module.dosomething()

Note that this requires you to be loading a specific module file,
it can't load a module laid out as a package.

Vampire can be found at:

   http://www.dscpl.com.au/projects/vampire

Note that I haven't done anything proper in PSP, so don't know how
practical it is to try and make use of the Vampire module loading
system. :-)

--
Graham Dumpleton (grahamd at dscpl.com.au)



More information about the Mod_python mailing list