Search code examples
pythonjsonapiflaskpymysql

Dynamic data wont change in flask


I'm trying to make an API in flask, but when I load up the API and then change the data in the database and reload the page the data doesn't change unless I restart the program. How do I make it so when the program is running and I change the data in the database I'll see it when I refresh the API in the browser? Thanks in Advance.

Here's the code:

from flask import Flask, jsonify, request 
import pymysql.cursors

connection = pymysql.connect(host='127.0.0.1',
user='root',
password='myroot',
db='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

app = Flask(__name__) 

@app.route('/', methods=['GET'])
def test():
    with connection.cursor() as cursor:
        connection.connect()
        sql = "SELECT * FROM importantData"
        cursor.execute(sql)
        result = cursor.fetchall()
    return jsonify(result)

@app.route('/locations', methods=['GET'])
def test1():
    with connection.cursor() as cursor:
        connection.connect()
        sql = "SELECT * FROM locations"
        cursor.execute(sql)
        result = cursor.fetchall()
    return jsonify(result)


    if __name__ == '__main__':
        app.run(port=8080) 

EDIT: The solution was that I had to open the database connection in every route function, edited the code so now it works as it's supposed to.


Solution

  • The solution was that I had to open the database connection in every route function, edited the code so now it works as it's supposed to