【问题标题】:Trying to use threading.Timer to run Flask app periodically尝试使用 threading.Timer 定期运行 Flask 应用程序
【发布时间】:2021-06-03 02:31:45
【问题描述】:
from flask import Flask, request, abort, render_template
from News.News import News, news1_title, news1_topline

app = Flask(__name__)
app.register_blueprint(News, url_prefix="/News")

@app.route('/')
def index():
    return render_template(
    'index.html',
    news1_title_html = news1_title,
    news1_topline_html = news1_topline,
    )
    threading.Timer(30, index).start()

index()


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

我试图让 Flask 应用程序每 30 秒运行一次,以便为我的 Flask 服务器刷新来自新闻网站的解析数据。数据通过 html 模板 (index.html) 显示。我得到一个 AttributeError: 'NoneType' object has no attribute 'app' 并且 render_template 似乎有问题。

我对此很陌生,如果这是一个愚蠢的问题,对不起。

【问题讨论】:

    标签: python flask timer attributeerror


    【解决方案1】:

    你尝试过添加

    <meta http-equiv="refresh" content="30" >
    

    在您的 HTML 中?

    你的应用是什么样的?

    基本烧瓶应用程序:

    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def home ():
        return render_template("index.html")
    # I'd go with debug for now:
    if __name__ == '__main__':
        app.run(debug=True)
    

    我认为你可以通过多种方式做到这一点:

    1. 使用调度器:

       from appscheduler.scheduler import Scheduler
      
       sched = Scheduler()
      
       def func_for_getting_news:
           #get the news
       sched.add_interval_job(funcfor_gettin_news, minutes=1)
      
    2. 使用线程:

    导入线程

    def myApiCall(): 
        # your request lib here making an http call ... 
        # call myApi() again in 600 seconds/10min 
        threading.Timer(60, myApiCall).start() 
     
    myApiCall() 
    

    【讨论】:

    • 问题是,当像这样刷新 html 时,输入它的变量保持不变。是的,这就是我的烧瓶应用程序的外观,另外我加载了一些执行解析工作的蓝图。没有计时器它工作正常。我添加了上面的代码。
    • 您如何收集数据?你为什么要运行 index() ?创建路线后?
    • 我使用 requests.get(url) 从网站获取数据,请求和解析发生在蓝图“新闻”中。我不确定,我以为我正在创建路线“/”,然后运行应用程序 index() 以用我的 html 模板和内容填充该路线?
    • 无需运行 index() 。可能重新阅读文档? (上帝,我真的很讨厌这样的 cmets :-D)写一个函数。为您获取新闻数据并在最后使用线程?
    • 好吧,我想我明白了。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2022-01-18
    • 1970-01-01
    • 2012-02-15
    • 2015-06-16
    • 2015-08-14
    • 2016-01-19
    相关资源
    最近更新 更多