Welcome to the most important section on building a flask app, but also the quickest and easiest to understand.
1 - URL Routing explained
Remember when we talked about Python decorators last time? They’re those lines that start with @, like @app.route("/"), and they help Flask know what to do when someone visits a specific part of our website. For example, when we used @app.route("/"), it meant that the function right under it should run when someone goes to the main page of our site without any extra bits in the URL.
Now, we’re setting up our flask app so you can go to different URLs like site.com/bbc or site.com/cnn to pick news from different sources.
First up, we need to grab the RSS feeds from these news sources. Here are a few links that work right now:
CNN: http://rss.cnn.com/rss/edition.rss
BBC: http://feeds.bbci.co.uk/news/rss.xml
Fox: http://feeds.foxnews.com/foxnews/latest
Iol: http://www.iol.co.za/cmlink/1.640
We’ll start by using what’s called static routing for just two of these to see how it works. Static routing isn’t the best way, but it’s good for a start. Later, we’ll switch to dynamic routing, which is a smarter way to handle different URLs without setting each one up individually.
Instead of making a separate variable for each RSS feed, we’re going to put them all in a Python dictionary. This way, our get_news() function can stay simple and flexible—we just tell it which news source we want based on the URL, and it handles the rest. Here’s how our updated code will look:
import feedparser
from flask import Flask
app = Flask(__name__)
RSS_FEEDS = {'bbc': 'http://feeds.bbci.co.uk/news/rss.xml',
'cnn': 'http://rss.cnn.com/rss/edition.rss',
'fox': 'http://feeds.foxnews.com/foxnews/latest',
'iol': 'http://www.iol.co.za/cmlink/1.640'}
@app.route("/")
@app.route("/bbc")
def bbc():
return get_news('bbc')
@app.route("/cnn")
def cnn():
return get_news('cnn')
def get_news(publication):
feed = feedparser.parse(RSS_FEEDS[publication])
first_article = feed['entries'][0]
return """<html>
<body>
<h1>Headlines </h1>
<b>{0}</b> </ br>
<i>{1}</i> </ br>
<p>{2}</p> </ br>
</body>
</html>""".format(first_article.get("title"), first_article.get("published"), first_article.get("summary"))
if __name__ == "__main__":
app.run(port=1234)
This is what you see when you boot it up:
2 - Code Breakdown
This code sets up a simple web app using Flask, which displays news articles
Keep reading with a 7-day free trial
Subscribe to Data Science & Machine Learning 101 to keep reading this post and get 7 days of free access to the full post archives.