python - 在 SQLAlchemy 中创建一列 "immutable"

标签 python sqlalchemy flask-sqlalchemy

我想在 SQLAlchemy 中使列“不可变”或“不可更新”。

现在我正在使用一个事件监听器,如果该列被更新,它会引发异常:

@event.listens_for(Person.email, 'set')
def receive_set_person_email(target, value, old_value, initiator):
    if old_value != symbol('NEVER_SET') and old_value != symbol('NO_VALUE'):
        raise AttributeError("Cannot change a Person's email")

但我想知道是否已经内置了类似的东西,或者我是否可以获得更漂亮、更通用的解决方案。

最佳答案

这是我的解决方案:

from sqlalchemy import event
from sqlalchemy.util.langhelpers import symbol


class NonUpdateableColumnError(AttributeError):
    def __init__(self, cls, column, old_value, new_value, message=None):
        self.cls = cls
        self.column = column
        self.old_value = old_value
        self.new_value = new_value

        if message is None:
            self.message = 'Cannot update column {} on model {} from {} to {}: column is non-updateable.'.format(
                column, cls, old_value, new_value)


def make_nonupdateable(col):
    @event.listens_for(col, 'set')
    def unupdateable_column_set_listener(target, value, old_value, initiator):
        if old_value != symbol('NEVER_SET') and old_value != symbol('NO_VALUE') and old_value != value:
            raise NonUpdateableColumnError(col.class_.__name__, col.name, old_value, value)


class Person(Base):
    email = Column(String)

make_nonupdateable(Person.email)

关于python - 在 SQLAlchemy 中创建一列 "immutable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953759/

相关文章:

python - Python 中 geoalchemy2 的 Spatialite 后端

python - Sqlalchemy 枚举迁移更新失败说不存在

python - 跨数据库加入sqlalchemy

python win32com excel边框格式化

python - Mayavi 中的基本 3D 体素网格

python - 我怎样才能在 Django 模板中做到这一点

python - Pytest:设置测试客户端和数据库

python - 一次写入只读字段

python - Django 模板标签显示对象的错误日期

python - 跨项目重用 SQLAlchemy 模型