14.8. Web Applications With a User Interface

This section builds on the material in the preceding sections to present a web application that prompts the user to provide input, performs some processing, and displays results.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 from flask import Flask, request

 app = Flask(__name__)

 @app.route('/')
 def home():
     return HOME_HTML

 HOME_HTML = """
     <html><body>
         <h2>Welcome to the Greeter</h2>
         <form action="/greet">
             What's your name? <input type='text' name='username'><br>
             What's your favorite food? <input type='text' name='favfood'><br>
             <input type='submit' value='Continue'>
         </form>
     </body></html>"""

 @app.route('/greet')
 def greet():
     username = request.args.get('username', '')
     favfood = request.args.get('favfood', '')
     if username == '':
         username = 'World'
     if favfood == '':
         msg = 'You did not tell me your favorite food.'
     else:
         msg = 'I like ' + favfood + ', too.'

     return GREET_HTML.format(username, msg)

 GREET_HTML = """
     <html><body>
         <h2>Hello, {0}!</h2>
         {1}
     </body></html>
     """

 if __name__ == "__main__":
     # Launch the Flask dev server
     app.run(host="localhost", debug=True)

The program is organized as follows:

You have attempted of activities on this page