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 "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:
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; however, there are certain restrictions that apply. web2py provides alocal_import function that must be used to import modules from the "modules" folder. Here is an example of usage:
1. | mymodule = local_import('mymodule') |
The function looks for mymodule in the app local modules folder and imports it with the name on the left-hand side of equal.
This function takes three arguments: name, reload and app. When you specify reload=True, it will re-import the module upon each request; otherwise your python process will only import the module once. The default is reload=False. app is the name of the application from which to import the module, it defaults to request.application.