title: How to use PostgreSQL with SQLAlchemy in a Flask application with Redis queued job
body: <p>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: <code>RuntimeError: No application found. Either work inside a view function or push an application context.</code> The function is stored in a separate file, not <code>app.py</code>.</p>
  <p>My <code>app.py</code>:</p>
  <pre><code>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)
  </code></pre>
  <p>in my <code>models.py</code> the setup_db look like this:</p>
  <pre><code>db = SQLAlchemy()
  
  
  def setup_db(app):
      database_name = 'dev'
      default_database_path = &quot;postgresql://{}:{}@{}/{}&quot;.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)
  </code></pre>
  <p>And then in a function that gets triggered when I enqueue job I call:</p>
  <pre><code>users = User.query.all()
  </code></pre>
  <p>where User is a db model I have defined in my <code>models.py</code>.</p>