Karrigell/Write an interactive application in a single script

From Wikibooks, open books for an open world
< Karrigell
Jump to: navigation, search

Edit the same script, index.py, like this :

def index():
	form = FORM(action="show")
	form <= INPUT(name="city")
	form <= INPUT(Type="submit",value="Ok")
	return HTML(BODY(form))
def show(city):
	return city

This script defines 2 functions, index() and show(). In index() we build an HTML form, in show() we handle the data entered in the form

In function index() we first create an HTML form with the class FORM, with the parameter "action" set to "show", the name of the function that will handle the data entered by the user

Then we build this form with INPUT instances. For this we "add a child" to the FORM instance with the operator <= (think of it as a left arrow, meaning "add child") : first an input tag with name "city", then a submit tag with value "Ok". Note that the attribute "type" is written Type with an uppercase initial, to avoid confusion with the Python name "type"

When the script is called by http://localhost/index.py/index, the form is printed in the web browser. Enter a value in the input field, then click on "Ok" : the value in the address bar of your browser will be set to http://localhost/index.py/show?city=..., and you will see the data you entered

How does this work? The value entered in the field "city" is passed as the argument to the function show() - the "action" attribute of the form. This function just returns this value, so the browser prints it

The name of the arguments of the function that receives the HTML form must be the same as the names in the HTML form. You can also use the usual Python syntax for unspecified arguments :

def show(**kw):
	return kw['city']