How to fix "RuntimeError: Working outside of application context." when creating blueprints with Flask?

How to fix "RuntimeError: Working outside of application context." when creating blueprints with Flask?

我正在尝试创建一个蓝图并 运行 解决这个问题:

Traceback (most recent call last):
  File "C:\Users\Max\PycharmProjects\python1\flask_first\__init__.py", line 3, in <module>
    from models import db
  File "C:\Users\Max\PycharmProjects\python1\flask_first\models.py", line 5, in <module>
    current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html'  # access to the SQL
  File "C:\python3.9\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\python3.9\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
    return self.__local()
  File "C:\python3.9\lib\site-packages\flask\globals.py", line 52, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

我已经做了很多研究,但对我没有任何用处(或者我只是看起来不够正确)。

这是models.py代码:

from flask_sqlalchemy import SQLAlchemy
from flask import current_app


current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html'  # access to the SQL
current_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(current_app)

class users(db.Model):
    __tablename__ = 'users'
    _id = db.Column('id', db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    email = db.Column(db.String(120))
    password = db.Column(db.Integer)

    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password = password

这是 __init__.py:

from datetime import timedelta
from flask import Flask
from models import db
from flask_first.admin.second import second

def create_app():
    app = Flask(__name__)
    with app.app_context():

        db.init_app(app)
    return app

create_app.secret_key = 'hello world'
create_app.permanent_session_lifetime = timedelta(minutes=5)  # setting the time for long-lasting session

if __name__ == '__main__':
    db.create_all()
    create_app.run(debug=True)

这是我的结构的截图:

在这里,我将 扩展为一个答案。

Python 逐行执行您的代码,其中包括 import 语句。如错误所示,当它输入 __init__.py 并到达 from models import db 行时,它 立即 跳转到 models.py,并开始在那里执行你的行.

Traceback (most recent call last):
  File "...\__init__.py", line 3, in <module>
    from models import db
  File "...\models.py", line 5, in <module>
    current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html'

此时导入的current_app还不存在,因为__init__.pycreate_app好像还没有被调用。在这里您会遇到常见的 Flask 错误“在应用程序上下文之外工作:

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

大多数时候您会遇到此类错误,解决方法是重新排序您的初始化代码。请确保 Flask 应用程序实例已经创建,然后再执行任何其他操作。它通常应该是您的代码所做的第一件事。

Quickstart tutorial from flask-sqlalchemy 之后,您可以将 db 对象初始化放在 app 初始化附近。

# Create app object
app = Flask(__name__)

# Set configs
app.config['...'] = ...

# Create db object
db = SQLAlchemy(app)

appdb 对象通常 一起 驻留在某些顶级主模块中。然后,在您需要单独设置每个组件的其他子模块(控制器、模型等)中,从主模块导入 app and/or db

from some_main_module import app, db

# Do stuff with app and db