分配给未映射到 SQLAlchemy 列的属性时如何引发异常? [英] How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column?

查看:21
本文介绍了分配给未映射到 SQLAlchemy 列的属性时如何引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SQLAlchemy,我发现有时我会错误地输入映射到列的属性名称,这会导致很难捕获错误:

With SQLAlchemy, I'm finding that sometimes I mis-type a name of an attribute which is mapped to a column, which results in rather difficult to catch errors:

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 列的任何内容会引发异常?

Is there a way to configure the mapped class so assigning to anything which is not mapped to an SQLAlchemy column would raise an exception?

推荐答案

好吧,解决方案好像是重写基类的 __setattr__ 方法,这样我们就可以检查属性是否已经存在在设置之前.

Ok, the solution seems to be to override __setattr__ method of the base class, which allows us to check if the atribute already exists before setting it.

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 http://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 的严格模式"...

Sort of "strict mode" for SQLAlchemy...

这篇关于分配给未映射到 SQLAlchemy 列的属性时如何引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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