SQLAlchemy中的动态类创建 [英] Dynamic Class Creation in SQLAlchemy

查看:349
本文介绍了SQLAlchemy中的动态类创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要创建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.

谢谢...

推荐答案

您可以使用MyObject ="noreferrer">对type 的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中的动态类创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆