Want to learn how to build a web
application? This article provides the "hello world" of web
programming. You'll learn how to use Python and Google's App Engine to
create a dynamic page that says "hello" to the user. Dynamic Web PagesWhen a user enters a URL, clicks on a link, or submits a form in a web page, a request is sent to some server on the Internet. Some requests are simple and the server just returns a static web page in HTML format. Many requests, however, are for dynamic web pages such as that of a news site or social network. For these pages, the server invokes controller code which processes the request. The controller accesses information from a database, performs computations, and ultimately generates a new HTML page sent to a browser.An HTML template like a form letter in which the name and address can be automatically replaced so that the letter is sent out to many people. HTML templates consist of HTML code and template variables, which are the parts of the page that are replaced with "live" data such as a news item. In this lesson, we'll be using Google's App Engine and controller code written in the Python language. The HTML templates we'll use define anything within double-curly-brackets as a template variable, e.g., <html> <body> Dear {{recipient}}, <p>You are a nice man</p> </body> </html> HTML FormsFor command-line programs written in Python, we use the 'input' and 'raw-input' functions to get input data from the user. With web applications, our user interface is HTML and we get input from the user with an HTML component called a form. <form action="/say_hello" method="get"> application = webapp.WSGIApplication(first:<input type="text" name="first"><br/> last:<input type="text" name="last"><br/> <input type="submit" value="Say Hello"> </form> If this HTML were rendered in a browser, you'd see: The form consists of a set of input components. In the example, there are two text components, one named 'first', the other named 'last', and a submit button. Web applications are based on the client-server model. The web page runs on the client (the browser). When the user clicks on a submit button, a request is made to the server using the data defined within the form. Let's pretend our example came from the server http://sample.com, and say the user entered 'Joe' and 'Smith' in the text boxes and then clicked 'Say Hello'. Then the following URL would be invoked: http://sample.com/say_hello?first=Joe&last=Smith Here 'say_hello' is the action defined in the form, and first and last are the names of the text boxes within the form. The URL is something like a function call in Python, where the function is say_hello, the formal parameters are first and last, and the actual parameters are 'Joe' and 'Smith'. Here, the browser sends a request to the server, sample.com. The server processes the request and sends back a new page, with result information, to the browser. Responding to Forms: The ControllerWe call the web server code that handles requests the controller. With a Google App Engine server, your controller code maps a request action to a controller class method. The mapping table is defined near the bottom of the controller file:[ ('/', MainPage), ('/say_hello', SayHelloHandler) # map request to a class ], debug=True) For this example, the /say_hello action is mapped to the class SayHelloHandler. Most server code will define a number of actions that it can "handle". For instance, the sample above also maps the main page of the site, denoted with '/' to a class called MainPage. The definitions for each handler class are found elsewhere in the controller file. For example, the sayHelloHandler would look something like the following: class SayHelloHandler(webapp.RequestHandler): In this incomplete handler, the parameters 'first' and 'last' of the request are accessed through the self.request.get method. Note also that the handler code is in a get function to match the 'method=get' specified in the HTML form.def get(self): first=self.request.get('first') last=self.request.get('last') # do some computations, access database # set up template values # render a page for the browser Generally, the server code will use the input parameters to access/modify a database, perform some computations, and ultimately render a new web page containing the results of the computations. For instance, the server code might access the personal profile matching the first and last name given in the parameters, then send this profile information as part of the rendered page. For our example, we'll just build a string which says hello to the user: class SayHelloHandler(webapp.RequestHandler): This
code creates a variable messageString that concatenates 'hello' with
the first name, e.g., 'hello Joe'. To get this string back to the
client, we stick it into a variable called 'template_values'.
template_values is a hash array that holds a list of key-value pairs.
In this case there is one key, 'message' which is mapped to the value
of the variable 'messageString'. def get(self): first=self.request.get('first') last=self.request.get('last') # set up template value messageString = 'hello ' + first template_values={'message': messageString} path = os.path.join(os.path.dirname(__file__),'response.html') self.response.out.write(template.render(path,template_values)) The second to last line in the controller code specifies that the file response.html should be rendered. response.html is called an 'HTML template', which is something like a form letter where the name and address can be automatically replaced so that the letter is sent out to many people. In this case, the replaceable part of response.html is the message, and it is specified with a template variable defined within double-curly brackets: <html> When the template is rendered, the {{message}} is replaced with the value that the controller defined in template_values, e.g., 'hello Joe'.<body> <p> {{ message }} </p> </body> </html> Other input typesThe above example is for text input, but HTML provides a number of other input widgets including radio buttons, checkboxes, and drop down listboxes. Check out this tutorial from http://www.w3schools.com/html/html_forms.asp for details.Your Turn1. Save the attachments
at the bottom of this page into a folder 'say_hello'. The easiest
way is to right-click on them and choose 'Save Link As'. Be sure and
name them exactly as they are named in the attachment.
2. We'll use the Linux command-line terminal to start up a test server. To open a command-line terminal, choose Applications | System | Terminal from the top menu. A black window should appear. 3. In the terminal window, make sure you are in the folder above the say_hello folder. If say_hello is in your home folder, you're fine. If say_hello is within a folder appEngineSamples, you'll need to first change directory into appEngineSamples: cd appEngineSamples Once you're in the right directory, start the local test server by entering the following: dev_appserver say_hello 4. The command above starts a development app server. This server is running on your local machine, but it acts as if it is a server somewhere on the Internet. You can test your program by opening a browser and entering the following URL in the address bar: http://localhost:8080 This will 'run' the program you just created by accessing the server you just started. Enter your first and last name and the program should respond by saying 'hello'. 5. If you've made it this far, your web app works, but its really not on the web yet-- your browser is just accessing a 'test' server on your local machine. Now we'll upload your application to the web, and specifically Google's App Engine servers:
6. To run your application, go to a browser and enter the name of your application, followed by 'appspot.com'. For instance, if your application identifier was 'DavesSayHello', then enter 'DavesSayHello.appspot.com' in your browser. If
all is well, you should see a web page that looks the same as when you
ran your program with the development server. Only this time, your
application is really running on the web. PART II. Modifying the code.1. First, let's make it so that the 'hello' appears directly on the home page (index.html) instead of in a separate file.
Hello Bob, your name has 3 letters in it. 3. Modify the controller so that, in the template values, it sends back the name and the number of letters in the name as two separate template values (name and nameLength). You can put more than one thing in the template_values by separating with commas, e.g., template_values = {'name':name, 'nameLength':nameLength} You'll also need to modify index.html so that it uses these template variables and has the sentence saying hello as part of the HTML. |

