搜尋

首頁  >  問答  >  主體

python - 请问以下Flask数据库配置哪里出错了呢?我是根据教程一步一步来做的:

请问以下Flask数据库配置哪里出错了呢?我是根据教程一步一步来做的:
教程: http://dormousehole.readthedocs.org/en/latest/tutorial/dbinit.html#tutorial-dbinit

#------code------
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for,abort, render_template, flash
from contextlib import closing

# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
​
# create our little application :)
app = Flask(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent = True)
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()

#------Runing in Python IDEL------
>>> from flaskr import init_db
>>> init_db()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "flaskr.py", line 22, in init_db
    with closing(connect_db()) as db:
  File "flaskr.py", line 19, in connect_db
    return sqlite3.connect(app.config['DATABASE'])
KeyError: 'DATABASE'
ringa_leeringa_lee2838 天前545

全部回覆(4)我來回復

  • 高洛峰

    高洛峰2017-04-17 12:05:02

    DATABASE = '/tmp/flaskr.db'應該是沒有問題的。
    在文件中加上這一行:

        app.config.from_object(__name__)
    

    就OK了,這行程式碼會從本檔案載入設定。

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-17 12:05:02

    DATABASE = '/tmp/flaskr.db' 這行配置,確認運作後能找到資料庫?有的話還得確認路徑相對或絕對 ? ?

    回覆
    0
  • PHPz

    PHPz2017-04-17 12:05:02

    sudo python

    回覆
    0
  • 阿神

    阿神2017-04-17 12:05:02

    1、configuration不做單獨檔案
    2、DATABASE 用絕對路徑

    回覆
    0
  • 取消回覆