RuntimeError: Работа вне контекста приложения с использованием Flask и Flask -Migrate - PullRequest
1 голос
/ 27 января 2020

Я пытаюсь написать модуль кеша, используя 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

Я пытался переместиться Migrate и Manage объекты от manage.py до extensions.py безуспешно. Я также попытался поместить их в with current_app.app_context(). К сожалению, это не приводит к исчезновению ошибки.

Каковы другие способы обеспечения доступа объектов к контексту?

EDIT : похоже, ошибка возникает из-за того, что 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()

Есть ли другое (возможно, более чистое) решение?

...