使用基于MySQL数据库的Flask更新网页。 [英] Updating the webpage using Flask based on MySQL database.

查看:878
本文介绍了使用基于MySQL数据库的Flask更新网页。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a webpage (built using HTML & jQuery) which displays the data from a MySQL database. I am using Flask to connect HTML with my database. However, my database gets updated every 15 minutes (using a separate Python Script). Currently, I stop the flask server, update the database and restart the Flask to update the webpage. My question is the following:

有没有办法在后台更新MySQL数据库,而不必停止烧瓶服务器?我读了关于AJAX和CRON的概念,但是我不能理解如何异步地使用它们。

Is there a way to update the MySQL database in the background without having to stop the flask server? I read about concepts of AJAX and CRON, however i am not able to understand how to use them with flask asynchronously.

注意:我是网络应用程序的新手,这是我第一个涉及连接客户端和服务器端的项目。

Note: I am a newbie in web applications and this is my first project which involves connecting client side and server side. Any help will be appreciated.

感谢

推荐答案

可能会做这样的事情:

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()

那么您的解决方案就是将您的连接和查询调用移动到您的控制器,以便每次您访问该页面时都重新查询数据库:

If that is the case, then your solution is simply to move your connection and query calls into your controller so that the database is re-queried every time you hit the page:

@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)

更新您的数据 - 您不必重新启动服务器,只是为了获取您的数据更改。

This way, your view will update when your data does - and you won't have to restart the server just to pick up changes to your data.

这篇关于使用基于MySQL数据库的Flask更新网页。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆