Fer said:
This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.
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.
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)
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>
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)
Show off your work to your peers by saving the file, running the app, and checking your work at http://localhost:5000.
python app.py
Share a screenshot and strut your stuff.
would be good to note in previous part that you can see the result here:
http://localhost:5000
in a browser. Furthermore, some more details on the code would be nice.. what does the @ thing do.. what is a route .. why '\'