Printing a list in Flask

Memhir_Yasue picture Memhir_Yasue · Jul 13, 2017 · Viewed 12.3k times · Source

I want the script to make a list of the news headlines that it grabs from Reddit and display them as a text output. However it seems like the return function prevents me from doing that as it only lists one title.

from flask import Flask
import praw
import config

app = Flask(__name__)

@app.route('/') 
def index():
    reddit = praw.Reddit(client_id=config.client_id, client_secret=config.client_secret, user_agent="...")

    for submission in reddit.subreddit('worldnews').controversial(limit=10):
        print(submission.title)

    return(submission.title)

if __name__ == "__main__":
    app.run(debug=True)

Answer

kemis picture kemis · Jul 13, 2017

There is an answer that shows you the easy way to do it but I wanted to show you how you can do it with templates because that is a much better practice:

main.py:

from flask import Flask
import praw
import config

app = Flask(__name__)

@app.route('/') 
def index():
    reddit = praw.Reddit(client_id=config.client_id, client_secret=config.client_secret, user_agent="...")
    reddit_data = []

    for submission in reddit.subreddit('worldnews').controversial(limit=10):
        reddit_data.append(submission.title)

    return render_template("show_reddit.html", data=reddit_data)

if __name__ == "__main__":
    app.run(debug=True)

templates/show_reddit.html:

{% for item in data %}
    <p> {{ item }} </p>
{% endfor %}

In the template you can use HTML normally and to print out stuff and make the for loop you use Jinja2.