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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值