This article is resolved pycharm in python shell operation of the database error: RuntimeError:. No application found Either work inside a view function or push an application context.
init file:
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 file:
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if __name__ == '__main__':
manager.run()
pycharm in interactive python shell as follows:
from app import create_app,db
db.drop_all()
Given the information as follows:
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.
Photo:
We know from the error message, this error is caused due to the view and context, after extensive searching I found that many online methods are not desirable, but there is a way is correct (correct is relative, escape).
Method: app added in python shell context:
1、app=create_app('development')
2、app.app_context().push()
Results are as follows:
Once you have the context, we can operate the database.
Reference: https://github.com/gnu4cn/flaskLearnings/blob/master/10_flask-SQLAlchemy.md