RuntimeError:使用Flask和Flask-Migrate在应用程序上下文之外工作

我正在尝试使用flask和flask-migrate编写一个缓存模块。我收到以下错误:

Traceback (most recent call last):
  File "manage.py",line 7,in <module>
    migrate = Migrate(current_app,db)
  File "F:\gog-cache\venv\lib\site-packages\flask_migrate\__init__.py",line 49,in __init__
    self.init_app(app,db,directory)
  File "F:\gog-cache\venv\lib\site-packages\flask_migrate\__init__.py",line 55,in init_app
    if not hasattr(app,'extensions'):
  File "F:\gog-cache\venv\lib\site-packages\werkzeug\local.py",line 348,in __getattr__
    return getattr(self._get_current_object(),name)
  File "F:\gog-cache\venv\lib\site-packages\werkzeug\local.py",line 307,in _get_current_object
    return self.__local()
  File "F:\gog-cache\venv\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.

这是我的代码:

app.py

import os
from flask import flask


def create_app(config=os.environ['GOG_CACHE_APP_SETTINGS']):
    app = flask(__name__)
    app.config.from_object(config)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    with app.app_context():
        register_extensions(app)
        from cache import cache
        app.register_blueprint(cache)
    app.app_context().push()

    return app


def register_extensions(app):
    from extensions import db
    db.init_app(app)


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

manage.py

from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from flask import current_app
from extensions import db


migrate = Migrate(current_app,db)
manager = Manager(current_app)

manager.add_command('db',MigrateCommand)


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

extensions.py

from flask_sqlalchemy import SQLAlchemy
from rq import Queue
from worker import conn


db = SQLAlchemy()
q = Queue(connection=conn)

我执行以下命令:

python manage.py db migrate

我尝试将MigrateManage对象从manage.py移到extensions.py,但没有成功。我还尝试将它们放在with current_app.app_context()中。不幸的是,它并不能使错误消失。

还有什么其他方法可以确保对象可以访问上下文?

编辑:看来是因为执行脚本时current_app不可用,所以出现了错误。我找到了解决方法,但对我来说似乎很脏。我更新了manage.py而不是current_app来导入应用工厂:

from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from extensions import db
from app import create_app

app = create_app()
migrate = Migrate(app,db)
manager = Manager(app)

manager.add_command('db',MigrateCommand)


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

还有其他(可能更清洁)的解决方案吗?

YJX690271813 回答:RuntimeError:使用Flask和Flask-Migrate在应用程序上下文之外工作

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2703605.html

大家都在问