gpt4 book ai didi

python - 基于MySQL数据库使用Flask更新网页。

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:47 24 4
gpt4 key购买 nike

我有一个网页(使用 HTML 和 jQuery 构建)显示来自 MySQL 数据库的数据。我正在使用 Flask 将 HTML 连接到我的数据库。但是,我的数据库每 15 分钟更新一次(使用单独的 Python 脚本)。目前,我停止 flask 服务器,更新数据库并重新启动 Flask 以更新网页。我的问题如下:

有没有办法在不停止flask服务器的情况下在后台更新MySQL数据库?我阅读了有关 AJAX 和 CRON 的概念,但是我无法理解如何将它们与 flask 异步使用。

注意:我是网络应用程序的新手,这是我的第一个涉及连接客户端和服务器端的项目。任何帮助将不胜感激。

谢谢

最佳答案

你很可能在做这样的事情:

from flask import Flask, render_template
from yourMySqlLibrary import connect_to_mysql

conn = connect_to_mysql()
# This is only executed when you start the script
data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")

app = Flask(__name__)

@app.route("/")
def view_data():
return render_template("view_data.html", data=data)

if __name__ == "__main__":
app.run()

如果是这种情况,那么您的解决方案就是将您的连接和查询调用移到您的 Controller 中,这样每次您点击页面时都会重新查询数据库:

@app.route("/")
def view_data():
# Removed from above and placed here
# The connection is made to the database for each request
conn = connect_to_mysql()
# This is only executed on every request
data = conn.execute("SELECT * FROM MySemiRegularlyUpdatedTable")
return render_template("view_data.html", data=data)

这样,您的 View 将在您的数据更新时更新 - 并且您不必为了获取数据更改而重新启动服务器。

关于python - 基于MySQL数据库使用Flask更新网页。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14870553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com