CherryPy: Object-Oriented Web Development - A Simple Script
(Page 2 of 4 )
Before we start on a CherryPy application, we need to create a configuration file. This file governs the behavior of CherryPy. Here is a configuration file suitable for development work:
[global]
server.socketPort = 8080
server.environment = "development"
server.threadPool = 10
Name it development.conf. Most of it is pretty simple to understand. Under the “global” section, the server.socketPort variable controls which port your application will use. The server.environment variable can be set to either “development” or “production.” The former value will display tracebacks when an error is encountered, along with some very basic statistics at the bottom of each page. The latter value saves tracebacks, but it does not output them to the user's browser. Obviously, it doesn't append any statistics, either. We'll use the “development” option to mess around with, but when you expose your applications to the real world, you should always use the “production” option. The last variable we define, server.threadPool, simply tells CherryPy how many threads to spawn.
Now, we're ready to create a script. To do this, we simply create a class, and we set an instance of that class as CherryPy's root object. We then load the configuration file and start up CherryPy. Create a file called first.py to do this:
import cherrypy
class FirstApplication:
def index ( self ):
return "Hey."
index.exposed = True
cherrypy.root = FirstApplication()
cherrypy.config.update ( file = 'development.conf' )
cherrypy.server.start()
Now, run the script and point your browser to it:
http://localhost:8080
The index method is called. Notice that we set exposed to True. This makes the method publicly accessible. You will also notice some basic information at the bottom of this page. It looks quite ugly, but once “development” is changed to “production,” the information will go away. To check the traceback generated by the “development” option, simply throw an error:
import cherrypy
class FirstApplication:
def index ( self ):
raise TypeError
index.exposed = True
cherrypy.root = FirstApplication()
cherrypy.config.update ( file = 'development.conf' )
cherrypy.server.start()
Next: Expanding Your Application >>
More Python Articles
More By Peyton McCullough