python - 新人按着flask教程一步一步的走,报错..求指导...

 我家在波力牧场 发布于 2022-11-04 11:45

教程地址: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 "", line 1, in 
  File "flaskr.py", line 18, in init_db
    with closing(connect_db()) as db:
NameError: global name 'closing' is not defined
2 个回答
  • line2 直接改为from flask import * 加上import os
    DATABASE = '/tmp/flaskr.db' 如果是win把tmp改为所在的文件名

    2022-11-07 16:50 回答
  • from future import with_statement
    from contextlib import closing

    这两个导入你没做吧?

    2022-11-07 16:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有