This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Do Something Fun [Jan. 24, 2012, 8:36 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>

3) Render the Template