sometimesiwritecode
sometimesiwritecode

Reputation: 3223

How do I update my Flask app's data?

I am building a simple website using Python and Flask. I have noticed when I run the following command in terminal:

sudo python app.py

It sets everything up and makes my website accessible in a web browser from a local port. My problem is that my Flask app.py file does some web scraping and displays the results in the website when it is accessed.

Sadly, it seems this web scraped data does not update every time a person visits my website. Instead the web scraping code seems to run just once when I enter sudo python app.py and thus the results when one visits the URL are static. I would prefer app.py to run every time someone visits the site to get the most up to date, live scraped data. Is this possible and how would I do it with flask and python?

My app.py contains:

from flask import Flask, flash, redirect, render_template, request, session, abort
from sklearn.externals import joblib
import praw
import datetime
from operator import attrgetter
import sys
import numpy as np

class Post:
    def __init__(self, subreddit):
        self.subreddit = subreddit


class HotPost:
    def __init__(self, subreddit, ):
        self.subreddit = subreddit


reddit = praw.Reddit(client_id='myClientId',
                     client_secret='myClientSecret',
                     user_agent='pythonscript:com.example.hotandrisingcheckerandbarker:v0.1 (by /u/myusername)',
                     username='myusername',
                     password='mypassword')
subredditsToScan = ["Art", "videos", "worldnews"]
svm = joblib.load('modelSvm.pkl')
trendingPosts = []

for subreddit in subredditsToScan:
    for submission in reddit.subreddit(subreddit).hot(limit=150):

        trendingPosts.append(Post(subreddit))

app = Flask(__name__)

@app.route("/")
def index():
    #return "Flask App!"
    return render_template(
        'list.html',name=len(trendingPosts))

@app.route("/hello/<string:name>/")
def hello(name):
    return render_template(
        'list.html',trendingPosts=trendingPosts)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)

Upvotes: 0

Views: 997

Answers (1)

Chris
Chris

Reputation: 137114

When you load the page, the only part of your code that gets run is whatever is in the function attached to the relevant route. The part where you build trendingPosts only runs one time when you start the server.

If you move your for loop inside index() you should get the behaviour you're looking for:

@app.route("/")
def index():
    for subreddit in subredditsToScan:
        for submission in reddit.subreddit(subreddit).hot(limit=150):
            trendingPosts.append(Post(subreddit))

    return render_template(
        'list.html',name=len(trendingPosts))

Upvotes: 1

Related Questions