加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何在分配给未映射到SQLAlchemy列的属性时引发异常?

发布时间:2020-12-20 13:29:38 所属栏目:Python 来源:网络整理
导读:使用SQLAlchemy,我发现有时候我错误地键入了一个映射到列的属性的名称,这导致很难捕获错误: class Thing(Base): foo = Column(String)thing = Thing()thing.bar = "Hello" # a typo,I actually meant thing.fooassert thing.bar == "Hello" # works here,as
使用SQLAlchemy,我发现有时候我错误地键入了一个映射到列的属性的名称,这导致很难捕获错误:

class Thing(Base):
    foo = Column(String)


thing = Thing()
thing.bar = "Hello" # a typo,I actually meant thing.foo
assert thing.bar == "Hello" # works here,as thing.bar is a transient attribute created by the assignment above
session.add(thing)
session.commit() # thing.bar is not saved in the database,obviously
...
# much later
thing = session.query(Thing)...one()
assert thing.foo == "Hello" # fails
assert thing.bar == "Hello" # fails,there's no even such attribute

有没有办法配置映射类,因此分配给未映射到SQLAlchemy列的任何内容都会引发异常?

解决方法

好的,解决方案似乎是覆盖基类的__setattr__方法,这允许我们在设置之前检查属性是否已经存在.

class BaseBase(object):
    """
    This class is a superclass of SA-generated Base class,which in turn is the superclass of all db-aware classes
    so we can define common functions here
    """

    def __setattr__(self,name,value):
        """
        Raise an exception if attempting to assign to an atribute which does not exist in the model.
        We're not checking if the attribute is an SQLAlchemy-mapped column because we also want it to work with properties etc.
        See https://stackoverflow.com/questions/12032260/ for more details.
        """ 
        if name != "_sa_instance_state" and not hasattr(self,name):
            raise AttributeError("Attribute %s is not a mapped column of object %s" % (name,self))
        super(BaseBase,self).__setattr__(name,value)

Base = declarative_base(cls=BaseBase)

SQLAlchemy的“严格模式”排序……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读