So far, we've seen that the URL http://localhost:8000 triggers a call to the index method of the Root
class. The URL http://localhost:8000/viewResult triggers a call to the viewResult method of the Root
class.
- How does this magic work ?
- I know it cannot call the method of a class. It has to call the method of an instance of a class. How do you explain that ?
- What if I type the URL http://localhost:8000/dir1/dir2/dir3/page
Let's answer these questions:
First of all, when you declare a CherryClass in the source file:
CherryPy (or, to be more precise: the executable generated by CherryPy) will automatically create an instance of
this class, called className. This is the name of the class with a lower case first letter. (This is the reason
why CherryClass names should always start with an upper case letter)
This instance is a global variable and can be acces from anywhere in the program.
Based on the URL, how does CherryPy know which method of which class instance to call ?
It uses a simple mechanism:
For the URL host/dir1/dir2/dir3/page, it will call the dir1_dir2_dir3.page() method. So it will expect
your program to have a CherryClass called Dir1_dir2_dir3, which should have a method called page.
There are 2 special cases:
- if there is no first directory (in other words, the URL is in the form: host/page, then it will call the
root.page() method. This means that both URL host/page and host/root/page are perfectly equivalent.
- if there is no first directory and no page (in other words, the URL is just the host name), then it will call the
root.index() method.
Important: In CherryPy-0.9, a new feature was added: if the page http://localhost:8000/dir1/dir2/dir3 is
requested, CherryPy will convert it first to dir1_dir2.dir3(), so it will expect a dir3 method in the
Dir1_dir2 CherryClass. But if no such method exists, then it will look for an index method in the
Dir1_dir2_dir3 CherryClass. (this would also correspond to http://localhost:8000/dir1/dir2/dir3/index).
In the next chapter, we'll see how to use inheritance when we have similar modules inside a website...
See About this document... for information on suggesting changes.