How to prevent data from disappearing when refreshing web page?


In 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 :


and my data doesn’t show anymore. :

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")

def home():

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

if __name__== "__main__":

A piece of home.html :

    {% extends "template.html" %}
    {% block content %}
    {% for item in data %}
    {% endfor %}
    {% endblock %}

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


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

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

def close_connection(exception):
    db = getattr(g, '_dattabase', None)
    if db is not None:

def index():
    cur = get_db().cursor()
    cur.execute('SELECT * FROM data')
    rows = cur.fetchall()
    return render_template('index.html', rows = rows)

if __name__ == '__main__': = True)


        <title>SQLite in Flask</title>
        {% if rows %}
            {% for row in rows %}
                <li>{{ row[0] }}</li>
            {% endfor %}
        {% endif %}


output of flask sqlite select query


Answered By – arsho

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published