教程地址:http://docs.jinkan.org/docs/flask/tutorial/dbinit.html#tutorial-dbinit
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url _for, abort, render_template, flash
# 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') as f:
db.cursor().executescript(f.read())
db.commit()
if __name__ == '__main__':
app.run()
在Python shell 里创建数据库这一步报如下错误:
>>> init_db()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "flaskr.py", line 18, in init_db
with closing(connect_db()) as db:
NameError: global name 'closing' is not defined
from future import with_statement
from contextlib import closing
这两个导入你没做吧?