2017-06-01 65 views
0

我正在使用Python和Flask構建一個簡單的網站。如何更新我的Flask應用程序的數據?

sudo python app.py 

它設置的一切行動,使我的網站從本地端口Web瀏覽器訪問:當我在終端運行下面​​的命令我已經注意到了。我的問題是,我的Flask app.py文件會進行一些網頁抓取,並在網站訪問時在網站上顯示結果。

不幸的是,似乎這個網站抓取的數據並沒有每次訪問我的網站時更新。相反,當我輸入sudo python app.py時,網頁抓取代碼似乎只運行一次,因此訪問該網址時的結果是靜態的。我希望app.py每次有人訪問該網站時都會運行以獲取最新的實時刮取數據。這是可能的,我會怎麼做與燒瓶和蟒蛇?

app.py包含:

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) 
+0

是什麼在'app.py'? – Chris

+0

app.py containts所有我的代碼,刮擦網站以及@ app.route(「/ hello/ /」)和hello函數def告訴網站什麼.html頁面顯示他們 –

+0

描述它抽象isn' t非常有幫助。請[編輯]你的問題,並將最重要的部分添加爲[mcve]。 – Chris

回答

1

當加載頁面時,即獲取運行代碼的唯一部分是無論是在連接到相關的路由功能。當您啓動服務器時,您構建trendingPosts的部分僅運行一次。

如果移動內部index()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)) 
相關問題