7. Class, instance, method and URL

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.

Let's answer these questions:

First of all, when you declare a CherryClass in the source file:

CherryClass ClassName:

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:

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.