title: How to make SQLAlchemy engine available throughout the flask application?
body: <p>Sorry for the long question. I tried to keep it well formatted.</p>
  
  <p>How should i structure my application so that I can have the SQLAlchemy <code>engine</code> available throughout the application especially when I am using <code>Mixins</code> and custom <code>Base</code> class in models directory. Currently i am using something like this:</p>
  
  <pre><code>application/
  |── svc/
  │  |── service/
  │  | └─── service.py
  │  | └─── service2.py
  │  |── postgres/
  │  | └─── models/
  │  |  | └──── CustomBase.py
  │  |  | └──── User.py
  │  |──── connect.py
  |── scripts/
  │  |── mock_data/
  │  | └───── postgres_mock_data.py
  │  |──── db.py
  │  |──── load_data.py
  │  |──── commands.sh
  |── wsgi.py
  </code></pre>
  
  <p>My <code>connect.py</code> looks like this:</p>
  
  <pre><code>def connect_postgres(env_config=config['LOCAL']):
      """
      Function that sends host information to SQLAlchemy
      """
  
      # Omitted variables for brevity 
      connection_string = f'postgresql://{user}:{password}@{host}/{database}'
      engine = create_engine(connection_string, echo=True)
  
      return engine
  </code></pre>
  
  <p><code>service.py</code> also contains:</p>
  
  <pre><code>app = Flask(__name__)
  app.register_blueprint(service2, url_prefix='/endpoint2')
  </code></pre>
  
  <p><code>wsgi.py</code> looks like this:</p>
  
  <pre><code>from svc.postgres.connect import connect_postgres
  from svc.service.service import app as application
  config = configparser.ConfigParser()
  
  def startApp(env):
      connect_postgres(config[env])
      application.run(debug=True)
  
  if __name__ == "__main__":
      startApp('LOCAL')
  </code></pre>
  
  <p><code>CustomBase.py</code> looks like:</p>
  
  <pre><code>from sqlalchemy.ext.declarative import declared_attr
  from sqlalchemy.ext.declarative import declarative_base
  
  class CustomBase(object):
      @declared_attr
      def __tablename__(cls):
          return cls.__name__.lower()
  
      # Ommited for brevity
  
  Base = declarative_base(cls=CustomBase)
  </code></pre>
  
  <p><code>User.py</code> </p>
  
  <pre><code>from sqlalchemy import Column, String
  from CustomBase import Base
  
  class User(Base):
       name = Column(String)
       fullname = Column(String)
       nickname = Column(String)
  </code></pre>
  
  <hr>
  
  <p>I start my application with the command <code>python wsgi.py</code>.</p>
  
  <h2>Question:</h2>
  
  <p>How would I import <code>engine</code> and <code>session</code> in my <code>service.py</code> where the majority of SQL Queries will be performed. I want to avoid doing the following in <code>service.py</code> because it feels like it is redundant since i have already connected to postgres in the beginning of the application.</p>
  
  <pre><code>from svc.postgres.connect import connect_postgres
  engine = connect_postgres(config[env])
  </code></pre>
  
  <p>I think I know I obviously have to do this in <code>service.py</code> once <code>engine</code> is available:</p>
  
  <pre><code>from CustomBase import Base
  from sqlalchemy.orm import sessionmaker
  
  # Create all schemas
  Base.metadata.create_all(engine)
  
  # create a configured "Session" class
  Session = sessionmaker(bind=engine)
  
  # create a Session
  session = Session()
  </code></pre>
  
  <p>I know it is fairly simple to do the same with <code>flask-sqlalchemy</code> but I am bound to use the <code>SQLAlchemy</code> library. </p>
  
  <p><strong>flask-sqlalchemy code:</strong></p>
  
  <pre><code>db = SQLAlchemy(app)
  </code></pre>
  
  <p>I can use <code>db</code> in all the inherited blueprint apis.</p>
  
  <hr>
  
  <h2>EDIT: Potential answer</h2>
  
  <p>Should I just include <code>engine</code> in my <code>CustomBase.py</code> file and do a connection again?</p>
  
  <p><code>CustomBase.py</code> looks like:</p>
  
  <pre><code>from sqlalchemy.ext.declarative import declared_attr
  from sqlalchemy.ext.declarative import declarative_base
  from svc.postgres.connect import connect_postgres
  
  class CustomBase(object):
      @declared_attr
      def __tablename__(cls):
          return cls.__name__.lower()
  
      # Ommited for brevity
  
  Base = declarative_base(cls=CustomBase)
  engine = connect_postgres(config[env])
  </code></pre>
  
  <p><code>service.py</code></p>
  
  <pre><code>from CustomBase import Base, engine
  from User import User
  from sqlalchemy.orm import sessionmaker
  
  # Create all schemas
  Base.metadata.create_all(engine)
  
  # create a configured "Session" class
  Session = sessionmaker(bind=engine)
  
  # create a Session
  session = Session()
  </code></pre>
  
  <p>Although it still feels redundant to call <code>connect_postgres</code> function twice or should I just remove it from my <code>wsgi.py</code> (but i will have to hack my way into config variables at this point)?</p>