Do Something Fun [Jan. 24, 2012, 8:48 p.m.]
Finally, we get to the fun part. Instead of a joke punchline, let's now make our application display a working webpage showing a picture of you and a salutation. But instead of making that salutation a boring phrase that is the same every time, let's spice it up by showing a different hello message from you every time a user visits the page.
1) Create a List of Salutations
First thing we need is a list of saluations - four or five funny phrases where you say hello to the world. We can do this by putting a Python list in our application underneath the index function we wrote in the last step.
from flask import Flask import os app = Flask(__name__) @app.route('/') def index(): return "To conquer the human civilization on the other side." salutations = [ 'Hey there, hi there, ho there.', 'I am a banana.', 'Go Patriots!', 'Brian is nerf herder.'] if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) if port == 5000: app.debug = True app.run(host='0.0.0.0', port=port)
2) Create a Template
Next we need to create a template - a HTML file in which to render one of these random salutations. Flask expects these templatest to sit in a folder in your project fittingly calledtemplates. Create that folder and create a new blank file called index.html.
In this index.html, we can put any HTML we would like. What we'll do is use an img tag for your picture and then put your salutation as an h1 tag beneath it:
<html> <head> <title>My first Python website</title> </head> <body> <img src="http://example.com/path/to/your/photo.jpg" /> <h1>{{salutation}}</h1> </body> </html>
Everything here should look familiar except the {{salutation}} tag in the middle, which is not HTML. This is what Flask calls a template tag, which it populates with a variable you supply in your controller, which we will add to index() in the next step.
3) Render the Template
Now we'll put the two pieces together and finish the first pass at our website by rendering the template in our index() controller. First, we return to app.py and import the render_template function from Flask, along with choice from the random module to select a salutation at (you guessed it) random. Then we need to render a random salutation to the template.
from flask import Flask from flask import render_template import os from random import choice app = Flask(__name__) @app.route('/') def index(): salutation = choice(salutations) return render_template('index.html', salutation=salutation) salutations = [ 'Hey there, hi there, ho there.', 'I am a banana.', 'Go Patriots!', 'Brian is nerf herder.'] if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) if port == 5000: app.debug = True app.run(host='0.0.0.0', port=port)