Printing a list in Flask

巧了我就是萌 提交于 2020-01-11 10:37:53

问题


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)

回答1:


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.




回答2:


Given that code, the for is not doing anything.

The simplest way to get something working is to append each title to a list and return that array as text only. It should be something like:

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="...")
    list = []

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

    return("<p>" + "</p><p>".join(list) + "</p>")

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


来源:https://stackoverflow.com/questions/45072287/printing-a-list-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!