I’m trying to run some code at Flask startup, which uses the database (Flask-SQLAlchemy), but before any requests are taken. I read that @app.before_first_request
is deprecated, so what is the replacement.
If I don’t use the database, it works. But using the database, I get RuntimeError: Working outside of application context.
. I assume it’s because the app hasn’t been fully initialized yet
I have tried the following:
app.py
<code>def create_app():
nwm_app = Flask(__name__)
nwm_app.config |= {
"SQLALCHEMY_ENGINES": {
"default": "postgresql://postgres:postgres@localhost:5432/flask_test"
},
}
nwm_app.config.from_prefixed_env()
db.init_app(nwm_app)
alembic.init_app(nwm_app)
on_start()
# Register blueprints or views here
nwm_app.register_blueprint(calibration)
return nwm_app
</code>
<code>def create_app():
nwm_app = Flask(__name__)
nwm_app.config |= {
"SQLALCHEMY_ENGINES": {
"default": "postgresql://postgres:postgres@localhost:5432/flask_test"
},
}
nwm_app.config.from_prefixed_env()
db.init_app(nwm_app)
alembic.init_app(nwm_app)
on_start()
# Register blueprints or views here
nwm_app.register_blueprint(calibration)
return nwm_app
</code>
def create_app():
nwm_app = Flask(__name__)
nwm_app.config |= {
"SQLALCHEMY_ENGINES": {
"default": "postgresql://postgres:postgres@localhost:5432/flask_test"
},
}
nwm_app.config.from_prefixed_env()
db.init_app(nwm_app)
alembic.init_app(nwm_app)
on_start()
# Register blueprints or views here
nwm_app.register_blueprint(calibration)
return nwm_app
on_start.py
<code>def on_start():
with current_app.app_context():
with (db.session as session, session.begin()):
query = select(table)
result = session.execute(query)
print('results', result)
</code>
<code>def on_start():
with current_app.app_context():
with (db.session as session, session.begin()):
query = select(table)
result = session.execute(query)
print('results', result)
</code>
def on_start():
with current_app.app_context():
with (db.session as session, session.begin()):
query = select(table)
result = session.execute(query)
print('results', result)
The reason I need this is to do some database cleanup if the server previously ended abnormally