I have a python script which uses Flask-SqlAlchemy to access a Postgres database. However, whenever I try to query the database I receive a "working out of context" error. I figured the way to do this was to wrap it in app.app_context:
import psycopg2
import json
from simple_chalk import redBright
from ...models.bin import Bin
from ...models.station import Station
from ... import db
from datetime import datetime as dt
from ... import current_app as app
def findPositionBin(stationId, find_position):
    try:
        with app.app_context():
            result = Bin.query.filter_by(station_id=stationId).filter_by(position=find_position).first()
            print("result")
            return result
    except Exception as e:
        print(redBright(e))
However, to do so I would need to import app. The problem is that my root init.py has the app contained in a function to be called by wsgi.py to run the program.
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_socketio import SocketIO
from flask_cors import CORS
import eventlet
import threading
db = SQLAlchemy()
migrate = Migrate()
socketio = SocketIO()
def create_app():
    app = Flask(__name__, instance_relative_config=False)
    CORS(app)
    app.config.from_object('config.Config')
    eventlet.monkey_patch()
    socketio.init_app(app, cors_allowed_origins='*', async_mode='eventlet')
    migrate.init_app(app, db)
    with app.app_context():
        from . import routes
        from . import wsroutes
        from .models import user, bin, ip_port, station
        from .blueprints import user
        from .blueprints.CubeStation import station_routes
        from.database.CubeStation import station_database
        from .server import startServer
        from .blueprints.CubeStation.station_functions import broadcastLoop
        # from .database.CubeStation import station_database
        db.init_app(app)
        app.register_blueprint(user.user_blueprint)
        app.register_blueprint(station_routes.station_blueprint)
        # app.register_blueprint(station_database.database_blueprint)
        x = threading.Thread(target=startServer)
        x.start()
        t = threading.Thread(target=broadcastLoop)
        t.start()
        db.create_all()
        return app
Would anyone happen to know how I can expose the app so it can be imported by other modules? Or if there is a better approach to this. Thanks in advance
 
    