【问题标题】:Why is this Flask-SQLAlchemy code block executing twice?为什么这个 Flask-SQLAlchemy 代码块执行两次?
【发布时间】:2014-10-08 06:01:23
【问题描述】:

app.py 代码示例:

# imports here

app = Flask(__name__)
app.config.from_pyfile('app.cfg')
db.init_app(app)
with app.app_context():
    if os.path.exists('database/example.db'):
        print 'already exists'
    else:
        print 'database created'
        db.create_all()


#routes here

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

在初始加载时,它将打印“数据库已创建”,然后“已存在”。如果我在创建数据库后再次加载它,“已经存在”会打印两次。

already exists
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader
already exists

两部分问题:

1) 为什么 app.app_context() 块会执行两次?

2) 编写此代码的更好方法是什么?

【问题讨论】:

  • 正如输出所示,是自动代码重新加载器重新启动您的代码。每当您的代码在应用程序运行时发生更改时,它都应该这样做,它仅在调试模式下启用(也许您应该显示您的 app.cfg)。但是,在数据库已经存在的情况下,我真的看不到发生了什么变化,所以那里没有线索。

标签: python sqlite flask flask-sqlalchemy


【解决方案1】:

要了解会发生什么,请回到 Python 基础知识。当您键入python your_module.py 时,python 解释器将逐行读取(解释)您的代码。在这种情况下,它会在到达那里时执行您的with app.app_context 代码,并且您将第一次看到输出database create 或已经存在 下一次。接下来发生什么?解释器将简单地继续您的if __name__ == '__main__': 行,然后由于您直接运行它,它将调用app.run 方法,默认情况下debug 参数为True,它将以调试模式启动开发服务器并自动重新加载将重新启动您的代码(如@burnpanck 所述)。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多