问题描述
我们需要创建 SQLAlchemy 类来访问多个外部数据源,这些数据源的数量会随着时间的推移而增加.我们为核心 ORM 模型使用声明性基础,我知道我们可以使用 autoload=True 手动指定新的 ORM 类来自动生成映射.
We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM models and I know we can manually specify new ORM classes using the autoload=True to auto generate the mapping.
问题是我们需要能够动态生成它们,如下所示:
The problem is that we need to be able generate them dynamically taking something like this:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
stored={}
stored['tablename']='my_internal_table_name'
stored['objectname']='MyObject'
并动态地把它变成这样:
and turning it into something like this dynamically:
class MyObject(Base):
__tablename__ = 'my_internal_table_name'
__table_args__ = {'autoload':True}
我们不希望类的持续时间超过打开连接、执行查询和关闭连接所需的时间.因此,理想情况下,我们可以将上面存储"变量中的项目放入数据库中,并根据需要进行拉取.另一个挑战是对象名称(例如MyObject")可能用于不同的连接,因此我们无法定义一次并保留它.
We don't want the classes to persist longer than necessary to open a connection, perform the queries, and then closing the connection. Therefore, ideally, we can put the items in the "stored" variable above into a database and pull them as needed. The other challenge is that the object name (e.g. "MyObject") may be used on different connections so we cannot define it once and keep it around.
关于如何实现这一点的任何建议将不胜感激.
Any suggestions on how this might be accomplished would be greatly appreciated.
谢谢...
推荐答案
您可以使用 的 3 参数调用:
You can dynamically create MyObject
using the 3-argument call to type
:
type(name, bases, dict)
Return a new type object. This is essentially a dynamic form of the
class statement...
例如:
mydict={'__tablename__':stored['tablename'],
'__table_args__':{'autoload':True},}
MyObj=type(stored['objectname'],(Base,),mydict)
print(MyObj)
# <class '__main__.MyObject'>
print(MyObj.__base__)
# <class '__main__.Base'>
print(MyObj.__tablename__)
# my_internal_table_name
print(MyObj.__table_args__)
# {'autoload': True}
这篇关于SQLAlchemy 中的动态类创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!