Updating the webpage using Flask based on MySQL database.

随声附和 提交于 2019-12-22 09:48:34

问题


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:

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.

Thanks


回答1:


You are most likely doing something like this:

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.



来源:https://stackoverflow.com/questions/14870553/updating-the-webpage-using-flask-based-on-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!