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
- You can either use 4 whitespaces or one TAB to indent your code.
It is possible to use more or less than 4 whitespaces for indenting (for instance, 3 whitespaces) by using the -W option
to tell CherryPy about it (for instance: -W 3).
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.