As you'll program bigger websites, you'll soon feel the need to split your source code in several modules.
There are two ways to do this:
- Either your modules are completely independant. In this case, just create your files (for instance:
Hello1.cpy, Hello2.cpy and Hello3.cpy) and compile them
using:
python ../cherrypy.py Hello1.cpy Hello2.cpy Hello3.cpy
Note that the executable that CherryPy will generate will be called Hello1Server.py
- Or one module is needed by the other (for instance, one is a library used by the other one). In this case, all you
need to do is type the keyword use module on the very first line of the file. This works like an import
statement in Python. For instance, you can have:
***** File BoldTime.cpy: *****
import time
CherryClass BoldTime:
view:
def getBoldTime(self):
# Display the time in bold
return "<b>%s</b>"%time.time()
***** File Hello.cpy: *****
use BoldTime
CherryClass Root:
view:
def index(self):
return "<html><body>Hello, time is %s</body></hello>"%boldTime.getBoldTime()
To compile this, just use:
python ../cherrypy.py Hello.cpy
Five things to note:
- The use statement MUST be on the very first line of the file (don't put any comment before).
- CherryPy will automatically create a list of dependencies, and thus read the files in order and generate the
executable accordingly. If you create a loop in the dependencies, CherryPy will raise an error.
- The name of the CherryClass is BoldTime (with an upper case B). So is the name of the file and the name
you use in the use statement. But when you call boldTime.getBoldTime, a lower b is used, because it
refers to the instance of the class that is automatically created.
- You can still use regular Python import statements. (Either
import ...
or from ... import ...
)
- If you have lots of modules to include with use, then you can split the "use" statement on several lines (but they have
to be the first lines of the file). For instance, you can use:
****** File Root.cpy: *****
use HttpAuthenticate, CookieAuthenticate
use Mail, MaskTools
CherryClass Root:
mask:
def index(self):
OK
What if the modules are not in the same directory ?
Well, all you have to do is to use the -I option to compile the files. This allows you to specify the directories
where CherryPy will look for input files. For instance, if you have the following files:
/dir1/Module1.cpy
/dir2/Module2.cpy
Hello.cpy (uses Module1 and Module2)
Then you would compile Hello.cpy using:
python ../cherrypy.py -I /dir1 -I /dir2 Hello.cpy
By default, CherryPy will look in ., ../lib and ../src
You can also set an environment variable called CHERRYPY_HOME that contains the
name of the directory where CherryPy is installed. In this case, CherryPy will also look in CHERRYPY_HOME/lib
and CHERRYPY_HOME/src to find the modules.
In the next chapters, we'll learn how to use a few of CherryPy's standard library modules.
See About this document... for information on suggesting changes.