At the same level as the demo/ directory, create a directory called hello/.
Go to the hello/ directory and create a file called Hello.cpy that contain the following lines:
CherryClass Root:
mask:
def index(self):
<html><body>
Hello, world !
</body></html>
3.1
To compile the file, type:
python ../cherrypy.py Hello.cpy
This will create a file called HelloServer.py, which contains everything to run the website (including an HTTP server).
To start it, just type:
To see the page, open a browser and type in the URL: http://localhost:8000/
What we've learned:
- Source files for CherryPy are written using an extended version of the Python language (some parts use CherryPy's templating language)
- Source filenames for CherryPy have a .cpy extension and start with an upper case letter
- Just like any Python source file, CherryPy source files are indentation-sensitive. See the footnotes to find out more
about how CherryPy handles indentation.
- The
CherryClass
keyword is used just like the class
keyword in Python. The name of the CherryClass
must start with an upper case letter.
- Inside a CherryClass, you can define different sections, like
mask
, view
or function
. We'll see later
on how they are used an what they mean.
- Inside a section, you can define methods just like you would in Python. (i.e:
def index(self):
)
- The body for a mask method isn't written in Python. Instead, it's written in CHTL or CGTL which are CherryPy's
templating languages. We'll learn more about those languages later on.
- The file generated by CherryPy from an input file Foo.cpy is called FooServer.py
- The file generated by CherryPy is 100% pure Python
- When the browser requests the page at the root of the website,
root.index
gets called and its return value
is being sent to the browser
Now let's add some dynamic functionality to it...
Footnotes
- ... 3.1
- CherryPy's policy is that one
tab should be used to indent a block (it's easier to hit once the TAB key rather than 4 times the SPACE key).
However, we know that some people have some reasons not to use tabs (for instance, sending a program with tabs by email
or posting it to a newsgroup doesn't work very well). Therefore, it is also possible to use whitespaces to indent
blocks in CherryPy's source files. By default, CherryPy will expect 4 whitespaces for one indentation. If you use
something else (for instance, 3 whitespaces), then you have to use the -W 3 option to tell CherryPy about it. The
way it works is very simple: when it reads a file, CherryPy's preprocessor starts by replacing all occurences of
4 whitespaces (or 3, depending on the -W option) with one tab.
Please note that, unlike Python, one tab can never correspond to 2 indentation levels. It always corresponds
to one indentation level.
See About this document... for information on suggesting changes.