Querying model in Flask-APScheduler job raises app context RuntimeError Querying model in Flask-APScheduler job raises app context RuntimeError python python

Querying model in Flask-APScheduler job raises app context RuntimeError


Flask-SQLAlchemy requires an active app context to execute queries. While Flask-APScheduler does integrate APScheduler with Flask, it does not push an application context when running each job.

You'll need to push an app context in your job. Pushing an app context when setting up the extension doesn't do anything.

def my_job():    with app.app_context():        ...

You probably want an app context for all jobs. You can subclass the extension and override run_job.

from flask_apscheduler import APScheduler as _BaseAPSchedulerclass APScheduler(_BaseAPScheduler):    def run_job(self, id, jobstore=None):        with self.app.app_context():            super().run_job(id=id, jobstore=jobstore)            # super(APScheduler, self) in Python 2


I fixed this by adding the app to my instance of SQLAlchemy in the app factory:

def create_app():    new_app = Flask(__name__)    new_app.config.from_object('config')    new_app.secret_key = os.urandom(12)    db.init_app(new_app)    db.app = new_app    return new_app

I did try using the app context but that never worked.