我正在编写一个库,以使用SQLAlchemy与数据库进行通讯。我真的很喜欢SQLAlchemy的autoload_with=engine功能,该功能可以传递给Table构造函数以获取表的所有列,而无需程序员明确定义它们。
这是名为“ something”的表的基本方法:
Base = declarative_base()
engine = create_engine('mysql://user:pass@host/db_name')
table = Table('something', Base.metadata, autoload_with=engine)
class Something(Base):
__table__ = table
但是,我们有数据库的多个版本(在不同的主机上),因此我需要在运行时将引擎作为参数传递。我讨厌在模块中编写类似这样的内容,但是我想放弃一个更好的方法:
Base = declarative_base()
Something = None # gets defined after initialize() is called
def initialize(engine):
table = Table('something', Base.metadata, autoload_with=engine)
class _Something(Base):
__table__ = table
global Something
Something = _Something
然后,在使用任何SQLAlchemy模型之前,客户端代码必须执行以下操作:
import custom_db_api
engine = create_engine(...)
custom_db_api.initialize(engine)
是否有更好的方法来由外部调用者处理这种模块初始化?
慕丝7291255
相关分类