vendredi 16 juin 2017

What is a good pattern to use if one wants to use SQLAlchemy to connect to various DB from various applications?

Background:

This is the situation I am facing and so far my current solution seems rather clunky. I want to improve on it. Right now:

  • I setup connections to each database in the main function of the Pyramid application:
 def main(global_config, **settings):
    a_engine = engine_from_config(settings, 'A.')
    b_engine = engine_from_config(settings, 'B.')
    ASession.configure(bind=a_engine)
    BSession.configure(bind=b_engine)

  • "ASession" and "BSession" are simply globally defined scoped_session in /models/init.py.
ASession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

  • I define model base class like so. For example:
ABase = declarative_base()
class user(ABase):
   id = Column(Integer, primary_key=True)
   name = Column(String)

This somehow already doesn't feel very clean. But now that this model is supposed to be accessed from a different application, I also need to define the engine and connection again in that application. This feels extremely redundant.

Problem Abstracted:

Assume that there are 2 different databases:

A and B

Also assume that you want A and B to be accessible from 2 different applications (e.g.: Pyramid application, Tornado application) using the same model.

In short, how would one best pattern objects/models/classes/functions to produce clean non-redundant code?

Aucun commentaire:

Enregistrer un commentaire