pycharm shell中数据库操作报错 上下文错误 RuntimeError: No application found. context

本文为解决pycharm中python shell操作数据库报错:RuntimeError: No application found. Either work inside a view function or push an application context.

init文件:

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint,url_prefix='/auth')

    app.app_context().push()

    return app

manage.py文件:

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if __name__ == '__main__':
    manager.run()

pycharm中python shell交互如下:

from app import create_app,db
db.drop_all()

报错信息如下:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/chen/PycharmProjects/flask_cp7/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 971, in drop_all
    self._execute_for_all_tables(app, bind, 'drop_all')
  File "/Users/chen/PycharmProjects/flask_cp7/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 940, in _execute_for_all_tables
    app = self.get_app(app)
  File "/Users/chen/PycharmProjects/flask_cp7/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 912, in get_app
    'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. 

图片为:

由报错信息我们知道,这个错误是由于视图和上下文引起的,我在广泛的搜索以后,发现网上的许多方法都不可取,但是有一种方法是正确的(正确是相对的,逃)。

方法:在python shell中的app加入上下文:

1、app=create_app('development')

2、app.app_context().push()

效果如下:

有了上下文后,我们便可以对数据库进行操作了。

参考资料:https://github.com/gnu4cn/flaskLearnings/blob/master/10_flask-SQLAlchemy.md

猜你喜欢

转载自blog.csdn.net/hrbust_cxl/article/details/89763949