python - 操作错误 : no such table: entries

标签 python sqlite flask

我正在学习 Flask 框架并且正在关注 Flask tutorial .我逐行执行了本教程的每一步。最后我收到错误“sqlite3.OperationalError OperationalError:没有这样的表:条目”。我在 linux 机器上,以前从未使用过 sqlite。我不知道如何解决这个问题。 flaskr.py 的代码在下面

# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash



# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
# Load default config and override config from an environment variable
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'flaskr.db'),
DEBUG=True,
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)


def connect_db():
# """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def init_db():
    with app.app_context():
        db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
        db.commit()


def get_db():
#"""Opens a new database connection if there is none yet for the current application context."""
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
        return g.sqlite_db


@app.teardown_appcontext
def close_db(error):
#"""Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()



@app.route('/')
def show_entries():
    db = get_db()
    cur = db.execute('select title, text from entries order by id desc')
    entries = cur.fetchall()
    return render_template('show_entries.html', entries=entries)



@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
        db = get_db()
        db.execute('insert into entries (title, text) values (?, ?)',
        [request.form['title'], request.form['text']])
        db.commit()
        flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))



@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
        return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))



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

最佳答案

我发现了问题。我需要在执行代码之前先创建表。所以我只是打开 python shell 并键入以下命令。此函数在我的数据库中创建了所需的表。

 from flaskr import init_db
 init_db()

关于python - 操作错误 : no such table: entries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23971003/

相关文章:

Python 段错误?

python - 如何使用 kapteyn.kmpfit 计算具有 2 个或更多自变量的模型的置信带

python - 为什么在使用数组迭代并从中提取元素时在列表中打印数组([])?

python - 使用 Python 的动态表

python - 如何获取字符串中两个或多个重复字符的索引?

mysql - 基于单元格值的动态列选择

sqlite - 如何在更新 Web 数据库之前跟踪本地 SQlite 上的数据库更改

ios - Mobile Safari 无法创建 SQLite DB

python - 在 Flask-MongoAlchemy 中创建动态文档

python - 如何在 Flask 应用程序中使用 celery 将任务从一台服务器发送到另一台服务器