HomePython Page 4 - CherryPy: Object-Oriented Web Development
Handling User Input - Python
Python users who engage in web development may appreciate some CherryPy. It is an object-oriented web development framework that allows you to develop web applications easily. It can run on its own server, or behind Apache. Keep reading to learn more.
Your application is probably going to have to deal with user input somewhere along the line, and, fortunately, CherryPy makes user input easy to work with. User input is passed in the form of arguments to methods, like this:
def index ( self ): return "<form method='POST' action='submit'>\n" + \ "E-Mail: <input type='text' name='email' />\n" + \ "<br /><input type='submit' value='Submit' />\n" + \ "</form>" def submit ( self, email = None ): if email: return "Thank you for your submission, " + email + "." else: return "You have not submitted anything!" index.exposed = submit.exposed = True
In the above example, we set the default value of email to None, but, of course, you can set it to whatever value you would like. As you can see above, handling user input is not a complex issue. Simply make your function accept user input as arguments, and then manipulate or access those variables as needed.
Sessions are used to store user data in between pages. In order to access them in CherryPy, we must modify our configuration file a bit to enable sessions:
When the user first visits the page, he or she sees a form with a color field. When the user selects a value, that value is stored inside of a session, and a link back to the first page is displayed. This time, however, the user will see the name of the chosen color displayed in the chosen color. The form will also be visible so that the chosen color may be changed.
Sessions work fairly simply. Each session name is stored as a key, with the session's value stored as the value of that key. We can check for the existence of a particular key by using the has_key method of cherrypy.session. Again, however, sessionFilter.on must be set to True in order for sessions to be enabled in your CherryPy application.
Though there are quite a few different web development platforms available for Python, CherryPy stands out because it makes heavy use of object orientation. Each page is a method contained in an object, and the elements in a request match the names of objects and methods. Moreover, each CherryPy script is actually an independent server. Tasks such as accepting user input and manipulating user sessions are especially easy with CherryPy, and making CherryPy work behind Apache is an easy feat. CherryPy allows for simple, object oriented web development in a simple, object oriented language.