How to use PostgreSQL with SQLAlchemy in a Flask application with Redis queued job

257 Views Asked by At

When executing SQL queries using SQLAlchemy directly on API calls in Flask app they are executed successfully but when I try to perform one inside my function that gets executed using Redis job queue I get the following error: RuntimeError: No application found. Either work inside a view function or push an application context. The function is stored in a separate file, not app.py.

My app.py:

app = Flask(__name__)
app.secret_key = os.environ.get('FLASK_SECRET_KEY')

worker_queue = Queue('default', connection=conn)
worker_registry = StartedJobRegistry(queue=worker_queue)

# database configuration
setup_db(app)

in my models.py the setup_db look like this:

db = SQLAlchemy()


def setup_db(app):
    database_name = 'dev'
    default_database_path = "postgresql://{}:{}@{}/{}".format('postgres', 'password', 'localhost:5432', database_name)
    database_path = os.getenv('DATABASE_URL', default_database_path)
    app.config['SQLALCHEMY_DATABASE_URI'] = database_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.app = app
    db.init_app(app)

And then in a function that gets triggered when I enqueue job I call:

users = User.query.all()

where User is a db model I have defined in my models.py.

0

There are 0 best solutions below