首页 > 解决方案 > 在哪里放置更新数据库的预定功能,以免干扰?

问题描述

我正在使用 python 中的 schedule 模块来运行一个每 5 分钟更新一次 mysql 数据库的函数。

database_update_function.py

def update_aqi():
    query = db.select([Aqi.id, Aqi.City])
    result = db.engine.execute(query).fetchall()
    for each_city in result:
        current_city = each_city[1]
        current_id = each_city[0]
        aqi_response = get_aqi(current_city)
        returned_aqi_data = aqi_response['data']['aqi']
        returned_time = aqi_response['data']['time']['s']

        update_this = Aqi.query.filter_by(id=current_id).first()
        update_this.Aqi = returned_aqi_data
        update_this.time = returned_time
        db.session.commit()

    return "updated time at ...."

和安排这个的功能

def dbUpdate():
    schedule.every(5).minutes.do(update_aqi)
    While True:
        schedule.run_pending()
        time.sleep(1)
    pass

我已经尝试在调用我的 app.py 时运行该函数,但是它必须等待 5 分钟然后呈现主页。

还尝试在下插入 dbUpdate() 函数

@app.route("/")
def index():
    """Return the homepage."""
    dbUpdate()
    return render_template("index.html")

仍然需要等待,因此我尝试插入我的另一条路线,但这一切都延迟了这条路线必须做的事情。插入的最佳位置在哪里,因此它只是从后面跑而从不干扰?

标签: pythonflaskschedulerschedule

解决方案


1) 数据库级别 - 在 MySQL 中,您可以创建EVENT以定义的时间间隔运行的数据库。 更多在这里

2)您可以使用类似Celery的东西,它是一个异步任务队列。


推荐阅读