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 from flask import Flask, request
 2
 3 app = Flask(__name__)
 4
 5 @app.route('/')
 6 def home():
 7     return HOME_HTML
 8
 9 HOME_HTML = """
10     <html><body>
11         <h2>Welcome to the Greeter</h2>
12         <form action="/greet">
13             What's your name? <input type='text' name='username'><br>
14             What's your favorite food? <input type='text' name='favfood'><br>
15             <input type='submit' value='Continue'>
16         </form>
17     </body></html>"""
18
19 @app.route('/greet')
20 def greet():
21     username = request.args.get('username', '')
22     favfood = request.args.get('favfood', '')
23     if username == '':
24         username = 'World'
25     if favfood == '':
26         msg = 'You did not tell me your favorite food.'
27     else:
28         msg = 'I like ' + favfood + ', too.'
29
30     return GREET_HTML.format(username, msg)
31
32 GREET_HTML = """
33     <html><body>
34         <h2>Hello, {0}!</h2>
35         {1}
36     </body></html>
37     """
38
39 if __name__ == "__main__":
40     # Launch the Flask dev server
41     app.run(host="localhost", debug=True)

The program is organized as follows:

You have attempted of activities on this page