'Access flask app context in worker to access database

I am trying to access db.session in a Flask-RQ job to update my database.

The thing is that I am not able to do it as my app context is not known by the worker which is executing jobs.

I am also using Flask Blueprints to structure my application so I am not able to use app context with from app import app.

Below my application structure:

--> app
  --> __init__.py
  --> jobs.py
  --> routes
    --> routes.py
config.py

I created a Blueprint for jobs.py but when I trigger my job in routes.py file I have an error when trying to do query with db.session (note that db is imported with from app import db and session with from flask import session).

RuntimeError: No application found. Either work inside a view function or push an application context.

The job is pretty simple:

@rq.job
def try_rq():
    print("Starting task")
    db.session.query(...)
    print("Task completed")

I do not know how to make my worker knowing the application context and so be able to use db.session to update my database.

Note that without database update the job is working fine.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source