Build a Twitter Analytics App
2 The First Step: Design Your Solution
6 Writing the Backend Twitter Server
Writing the Code in Small Parts: Part 1, The Basic App
Part 2: Adding a Counter to Exit
Part 3: Adding Language and Retweet Count
7 Adding the Data to a Database
8 Testing: What and How to Test
9 Displaying our Data using the Flask Webserver
9.2 Adding templates to our Flask app
9.3 Displaying our Tweets in the Flask Web Server
10 Future Work and Improvements
Let’s add some templates to our code now. Make sure you’ve read the templates section in the Flask quickstart.
We are working with this file. We will be looking at parts of it:
1 2 3 |
@app.route("/top_tweets") def top_tweets(): return render_template("top_tweets.html") |
So we are calling the template top_tweets.html. This template inherits from index.html, so lets look at that first.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head> {% block graphs %} {% endblock %} </head> <body> {% block div %} {% endblock %} {% block tweets %} {% endblock %} </body> </html> |
The block sections are the ones that can be overridden. You see we have a graphs section for when we add graphs, a general div section and a tweets section.
Let’s look at our actual file, top_tweets.html:
1 2 3 4 5 6 7 8 9 10 |
{% extends "index.html" %} {% block tweets %} <b> Most Popular Tweets </b> {% for tweet in tweets %} {{ tweet | safe}} {% endfor %} {% endblock %} |
As you can see, we extend index.html, and override the tweets block.
We have a for loop, because as we will see in the next section, we send the tweets as a list, and we loop over each.
The code in the {{ }} blocks is the one replaced by Jinja2 (our template system) with the value we passed in. You will note I am doing a | safe at the end of tweet.
That’s because, by default, Jinja will sanitise the HTML for us. Which is good for most cases.
However, as we will see later, we are using Twitter’s Javascript function to display the tweets, and it doesnt like our sanitised tweets. So normally, you would be very careful when using safe. In this case, however, we know the Tweets came directly from Twitter, so we can assume they are safe (or you can sue Twitter!).
But yeah, be careful using the safe keyword. Never use it with user input.
The main route in our Flask file is fairly simple, so let’s look at a slightly more complicated example, the trends template file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{% extends "index.html" %} {% block tweets %} <h3> Trending On Twitter: </h3> {% for t in trend %} <strong> {{t | safe}} </strong> </br> {% endfor %} {% for t in trend_tweet %} {{t | safe}} {% endfor %} {% endblock %} |
This is slightly more complicated in that we for 2 for loops- the first for trends, the second for the tweets. But other than that, it is similar to the last one.
So now that we have our templates in place, it is time to send them real data. That’s what we’ll do in the next section.