I’m using Flask and SQLAlchemy (not flask-sqlalchemy)
I’m trying to get access to the flask config from my database code, but it’s telling me that I’m not in an application context, probably because the App is not yet fully initialized.
I have app.py
:
from flask import Flask
from root.views.calibration_views import calibration
nwm_app = Flask(__name__)
nwm_app.config.from_pyfile('myConfig.cfg')
print('config', nwm_app.config)
My calibration_views
file imports database.py
, which looks like this:
from sqlalchemy import URL, create_engine
from sqlalchemy.orm import sessionmaker
from flask import current_app as nwm_app
url = URL.create(
drivername="postgresql",
username="postgres",
password="postgres",
host="localhost",
database="flask_test"
)
engine = create_engine(url, echo=True)
with nwm_app.app_context():
print('config', nwm_app.config)
Session = sessionmaker(bind=engine)
I’m trying to get the config object using current_app
, which avoids the Python error about circular imports, but I still get
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
The nwm_app.app_context()
was my attempt to fix it, but it had no effect