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.
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.