python - 在哪里放置更新数据库的预定功能,以免干扰?
问题描述
我正在使用 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")
仍然需要等待,因此我尝试插入我的另一条路线,但这一切都延迟了这条路线必须做的事情。插入的最佳位置在哪里,因此它只是从后面跑而从不干扰?
解决方案
推荐阅读
- ios - Alamofire carthage 更新不适用于 Xcode 12 模拟器
- scala - 不同的单子用于理解
- python - 如何使用正则表达式使两个子组出现相同的次数?
- css - 如何使用 CSS 将换行的文本均匀分布在多行中?
- java - Java 不兼容类型:预期数量;找到整数
- ruby-on-rails - Ruby on Rails API 不会部署在 Amazon Elastic Beanstalk 上。找不到 gem 文件
- corda - 在 Corda 节点的 PostgreSQL 数据库中存储 JSON
- windows - Windows 10 更新后无法识别 Mocha
- c++ - 为什么 memset 可以用零初始化 C++ 中的 2D 数组,但在像这样声明 `array[n][k+1]={0}` 时无法设置?
- visual-studio-code - 使用 VS Code Dev Container 仅构建所需的 docker-compose.yaml 服务