sqlite3.OperationalError:没有这样的表,使用 SQLite 与 Flask 应用程序连接

问题描述 投票:0回答:1

我正在为我的最新任务学习 Flask,我尝试使用 SQLite 进行数据库连接,我 https://www.digitalocean.com/community/tutorials/how-to-use-the-sqlite3-module-in-python-3 为此,我创建了所有需要的文件,您可以在这里找到它们,并且没有错误,但是在运行 Flask 应用程序时,我得到了 sqlite3.OperationalError: no such table。 这是我的文件;首先是 schema.sql

DROP TABLE IF EXISTS posts;

CREATE TABLE posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    title TEXT NOT NULL,
    content TEXT NOT NULL
);

然后它将用于初始化数据库,所以这里是 init_db.py 文件

import sqlite3

connection = sqlite3.connect('database.db')


with open('schema.sql') as f:
    connection.executescript(f.read())

cur = connection.cursor()

cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
            ('First Post', 'Content for the first post')
            )

cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
            ('Second Post', 'Content for the second post')
            )

connection.commit()
connection.close()

这将创建我们将在 app.py Flask 应用程序文件中使用的database.db 文件:

from flask import Flask, render_template , request , redirect, url_for
import sqlite3

app = Flask(__name__)

def get_db_connection():
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn


@app.route('/db')
def index():
    conn = get_db_connection()
    posts = conn.execute('SELECT * FROM posts').fetchall()
    conn.close()
    return render_template('index.html', posts=posts)

最后这是模板文件:

{% extends "base.html" %}
{% block title %}
    db Page
{% endblock %}
{% block content %}
    <h1>{% block title %} Posts {% endblock %}</h1>
    {% for post in posts %}
        <div class='post'>
            <p>{{ post['created'] }}</p>
            <h2>{{ post['title'] }}</h2>
            <p>{{ post['content'] }}</p>
        </div>
    {% endfor %}
{% endblock %}

我真的迷失在烧瓶上的数据库连接和表单创建上,所以如果有人可以给我资源或建议,那将非常有帮助。 谢谢大家!!!

python database sqlite flask
1个回答
0
投票

在使用命令flask run启动应用程序之前,您需要先使用命令python init_db.py手动运行init_db文件。

© www.soinside.com 2019 - 2024. All rights reserved.