python flask 出现 KeyError: 'DATABASE'

正在学习Flask,按照官方的中文教程一步步执行后,到步骤 4: 创建数据库出现问题:
当时执行如下代码:

>>> from flaskr import init_db
>>> init_db() 

执行后报错:KeyError: ‘DATABASE’
而出错的地方就是按照教程一步步来写的如下代码:

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

即第三行中的DATABASE没有找到
后来网上查资料后发现,要做如下几个部分的修改:

1. 修改代码

需要在方法执行前添加如下语句:

DATABASE = app.root_path + '\\flaskr.db'
app.config.from_object(__name__)

最终添加完的完整代码为:

# encoding=utf8
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash

app = Flask(__name__)
DATABASE = app.root_path + '\\flaskr.db'
app.config.from_object(__name__)


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


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


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


@app.route('/')
def show_entries():
    cur = g.db.execute('select title, text from entries order by id desc')
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    return render_template('show_entries.html', entries=entries)


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

2. 安装SQLite数据库

下载SQLite数据库:https://www.sqlite.org/download.html,下载以下两项:

  • sqlite-dll-win64-x64-3280000.zip
  • sqlite-tools-win32-x86-3280000.zip

将2个文件解压到你想放的文件夹,然后在环境变量中添加这个文件夹的位置
在命令行中创建数据库:

D:\project\flaskr>sqlite3 flaskr.db
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.

用命令.database 查询系统中的数据库,确认数据库已经成功创建

sqlite> .database
main: D:\project\flaskr\flaskr.db

3. 执行Python程序,初始化数据库

>>> from flaskr import init_db()
>>> init_db()

你可能感兴趣的:(开发总结,Python,Flask)