gpt4 book ai didi

python - SQLAlchemy - 最大列长度

转载 作者:太空狗 更新时间:2023-10-30 00:00:42 24 4
gpt4 key购买 nike

在 SQLAlchemy 中是否可以强制分配给映射列的值的最大字符串长度?我只想在分配的字符串值比相应的字符串类型表列的长度长时引发异常。

谢谢

最佳答案

最简单的方法是重命名映射列并通过属性代理它:

class Something(Base):
...
_foo = Column('foo', String(123))

@property
def foo(self):
return self._foo

@foo.setter
def foo(self, value):
if len(value) > _foo.type.length:
raise Exception("Value too long")
self._foo = value

您可以轻松地分解出属性创建,甚至可以使用像 formencode 这样的通用验证框架。


如果您需要更具体的 SQLAlchemy 解决方案并且不介意使用特定接口(interface),那么 SQLAlchemy 具有用于捕获属性事件的扩展机制。使用它的验证器看起来像这样:

from sqlalchemy.orm.interfaces import AttributeExtension, InstrumentationManager
from sqlalchemy.orm import ColumnProperty

class InstallValidatorListeners(InstrumentationManager):
def post_configure_attribute(self, class_, key, inst):
"""Add validators for any attributes that can be validated."""
prop = inst.prop
# Only interested in simple columns, not relations
if isinstance(prop, ColumnProperty) and len(prop.columns) == 1:
col = prop.columns[0]
# if we have string column with a length, install a length validator
if isinstance(col.type, String) and col.type.length:
inst.impl.extensions.insert(0, LengthValidator(col.type.length))

class ValidationError(Exception):
pass

class LengthValidator(AttributeExtension):
def __init__(self, max_length):
self.max_length = max_length

def set(self, state, value, oldvalue, initiator):
if len(value) > self.max_length:
raise ValidationError("Length %d exceeds allowed %d" %
(len(value), self.max_length))
return value

然后,您可以通过在要验证的任何类上设置 __sa_instrumentation_manager__ = InstallValidatorListeners 来使用此扩展。如果您希望它应用于从它派生的所有类,您也可以只在基类上设置它。

关于python - SQLAlchemy - 最大列长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com