Search code examples
pythonhtmlsqliteflaskhttp-status-code-404

How to prevent data from disappearing when refreshing web page?


In app.py I established a connection with my database then retrieved the data and stored it in a cursor object. I want to show the data on a web page so I transferred it with :

render_template('home.html', data=cursor)

Which works, it shows the data on my web page but when I refresh the page I get :

GET http://127.0.0.1:5000/static/css/template.css net::ERR_ABORTED 404 (NOT FOUND)

and my data doesn't show anymore.

app.py :

from flask import Flask, render_template
import sqlite3
import os.path

app = Flask(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "movies.db")
with sqlite3.connect(db_path, check_same_thread=False) as db:
#I used check_same_thread=False to solve a same thread error 
     cursor = db.cursor()
     cursor.execute("SELECT * FROM data")

@app.route("/")
def home():

   return render_template('home.html', data=cursor)

if __name__== "__main__":
    app.run(debug=True)

A piece of home.html :

<body>
    {% extends "template.html" %}
    {% block content %}
    {% for item in data %}
    <tr>
        <td><a>{{item[1]}}</a></td>
    </tr>
    {% endfor %}
    {% endblock %}
  </body>

I want my web page to show the data without disappearing when I refresh my page.


Solution

  • According to the official documentation as @Fian suggested, you need to open the database connection on demand and close them when the context dies.

    Updated code for app.py:

    import os
    import sqlite3
    from flask import Flask, render_template, g
    
    app = Flask(__name__)
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    DATABASE = os.path.join(BASE_DIR, "movies.db")
    
    def get_db():
        db = getattr(g, '_database', None)
        if db is None:
            db = g._database = sqlite3.connect(DATABASE)
        return db
    
    @app.teardown_appcontext
    def close_connection(exception):
        db = getattr(g, '_dattabase', None)
        if db is not None:
            db.close()
    
    @app.route('/')
    def index():
        cur = get_db().cursor()
        cur.execute('SELECT * FROM data')
        rows = cur.fetchall()
        return render_template('index.html', rows = rows)
    
    if __name__ == '__main__':
        app.run(debug = True)
    

    index.html:

    <html>
        <head>
            <title>SQLite in Flask</title>
        </head>
        <body>
            <h1>Movies</h1>
            {% if rows %}
                <ul>                
                {% for row in rows %}
                    <li>{{ row[0] }}</li>
                {% endfor %}
                </ul>
            {% endif %}
        </body>
    </html>
    

    Output:

    output of flask sqlite select query

    Reference: