3

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

Prakhar Mehrotra
  • 1,215
  • 4
  • 16
  • 21
  • What happens if you don't stop the Flask server, what error do you get? – Doobeh Feb 14 '13 at 13:55
  • You say your database is updated every 15 minutes, then ask is there a wa to update the MySQL database in the background. As far as I can tell, that is what you're already doing with that separate python script. I really don't understand what you're asking here. – Mark Hildreth Feb 22 '13 at 04:14

1 Answers1

11

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.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • Yes, this is exactly what i was looking for. I was not connecting to my database from inside the controller. Thanks a lot :) – Prakhar Mehrotra Feb 22 '13 at 19:32
  • Could you please answer this question using jquery Ajax and a refresh interval of ??? 5 minutes. TIA. I think so the view updates from the browser..... – Merlin Feb 26 '13 at 03:47
  • Somewhat off-topic, but at what scope the objects initiated outside the controller live? Initialized only the first time the app is launched? Persisting across requests? – Passiday Mar 05 '14 at 14:29