如何防止刷新网页时SQLite数据消失

How to prevent SQLite data from disappearing when refreshing web page

我是第一次使用 phyton 和 SQLite 数据库,但遇到了一个问题。 在我的 app.py 文件中,我建立了与数据库的连接,然后检索数据并将其存储在游标对象中。我想在网页上显示数据库数据,所以我用

传输了它
render_template('home.html', data=cursor)

它可以正常工作,它会在我的网页上显示我想要的数据,但是当我刷新页面时,我得到

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

我的数据不再显示了。

我试图寻找解决方案,但没有找到解决我问题的方法。 您可以在下方找到我的 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)

我的一块 home.html :

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

我希望我的网页显示我想要的数据,而不会在我刷新页面时消失。我真的很想知道我做错了什么。

尝试将所有与连接和发出请求相关的代码移到请求处理函数中 (home())。此外,official documentation 可能会给您一些正确实施的提示。

根据@Fian建议的官方文档,您需要按需打开数据库连接,并在上下文死亡时关闭它们。

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>

输出:

参考: