0

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.

  • can you paste the full traceback error from the terminal. and your directory structure. so that we can see on which line and in which file the error is – charchit Jul 08 '21 at 09:49
  • BlazRupnik I would suggest you put all the files required to replicate the problem, each under different heading and denote, using comments maybe, where exactly the problem is. For example, I don't know where exactly `users = User.query.all()` call is. –  Jul 08 '21 at 13:31

0 Answers0