Third party modules

web2py is written in Python, so it can import and use any Python module, including third party modules. It just needs to be able to find them. As with any Python application, modules can be installed in the official Python “site-packages” directory, and they can then be imported from anywhere inside your code.

Modules in the “site-packages” directory are, as the name suggests, site-level packages. Applications requiring site-packages are not portable unless these modules are installed separately. The advantage of having modules in “site-packages” is that multiple applications can share them. Let’s consider, for example, the plotting package called “matplotlib”. You can install it from the shell using the PEAK easy_install command [easy-install] (or its modern replacement pip [PIP] ):

  1. easy_install py-matplotlib

and then you can import it into any model/controller/view with:

  1. import matplotlib

The web2py source distribution, and the Windows binary distribution has a site-packages in the top-level folder. The Mac binary distribution has a site-packages folder in the folder:

  1. web2py.app/Contents/Resources/site-packages

The problem with using site-packages is that it becomes difficult to use different versions of a single module at the same time, for example there could be two applications but each one uses a different version of the same file. In this example, sys.path cannot be altered because it would affect both applications.

For this kind of situation, web2py provides another way to import modules in such a way that the global sys.path is not altered: by placing them in the “modules” folder of an application. One side benefit is that the module will be automatically copied and distributed with the application.

Once a module “mymodule.py” is placed into an app “modules/“ folder, it can be imported from anywhere inside a web2py application (without need to alter sys.path with):

  1. import mymodule