有没有办法透明地执行SQ​​LAlchemy对象的验证? [英] Is there a way to transparently perform validation on SQLAlchemy objects?

查看:189
本文介绍了有没有办法透明地执行SQ​​LAlchemy对象的验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,我有一个方法可以在(或之后)属性设置之后执行验证,具有 mac 属性的域模型设备我想确保在$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

看起来像Pythonic的方法是做大多数事情作为属性(包括SQLAlchemy)。如果我用PHP或Java编码,我可能会选择创建getter / setter方法来保护数据,并给我在域模型本身处理这一点的灵活性。

  public function mac(){return $ this-> mac; } 
public function setMac($ mac){
return $ this-> mac = $ this-> sanitizeAndValidateMac($ mac);
}
public function sanitizeAndValidateMac($ mac){
if(!preg_match(self :: $ VALID_MAC_REGEX)){
throw new InvalidMacException($ mac);
}
return strtolower($ mac);
}

使用SQLAlchemy处理这种情况的Pythonic方法是什么? p>

(虽然我知道验证,应该在其他地方处理(即Web框架),我想知道如何处理这些域特定的验证规则,因为他们一定会经常出现。)



更新



我知道我可以在正常情况下使用属性。关键部分是我正在使用SQLAlchemy与这些类。我不明白SQLAlchemy如何执行其魔法,但我怀疑自己创建和覆盖这些属性可能会导致不稳定和/或不可预测的结果。

解决方案

您可以使用 @validates()装饰器在SQLAlchemy类中添加数据验证。



从文档 - 简单验证器


属性验证器可以引发异常,停止突变属性值的过程,或者将给定值更改为不同的值。来自sqlalchemy.orm的导入验证

class EmailAddress(Base):

$ b

  
__tablename__ ='地址'

id =列(整数,primary_key = True)
电子邮件=列(字符串)

@validates('email ')
def validate_email(self,key,address):
#你可以使用断言,如
#assert'@'在地址
#或引发一个例外:
如果'@ '不在地址中:
raise ValueError('电子邮件地址必须包含@符号')
返回地址


Is there a way to perform validation on an object after (or as) the properties are set but before the session is committed?

For instance, I have a domain model Device that has a mac property. I would like to ensure that the mac property contains a valid and sanitized mac value before it is added to or updated in the database.

It looks like the Pythonic approach is to do most things as properties (including SQLAlchemy). If I had coded this in PHP or Java, I would probably have opted to create getter/setter methods to protect the data and give me the flexibility to handle this in the domain model itself.

public function mac() { return $this->mac; }
public function setMac($mac) {
    return $this->mac = $this->sanitizeAndValidateMac($mac);
}
public function sanitizeAndValidateMac($mac) {
    if ( ! preg_match(self::$VALID_MAC_REGEX) ) {
        throw new InvalidMacException($mac);
    }
    return strtolower($mac);
}

What is a Pythonic way to handle this type of situation using SQLAlchemy?

(While I'm aware that validation and should be handled elsewhere (i.e., web framework) I would like to figure out how to handle some of these domain specific validation rules as they are bound to come up frequently.)

UPDATE

I know that I could use property to do this under normal circumstances. The key part is that I am using SQLAlchemy with these classes. I do not understand exactly how SQLAlchemy is performing its magic but I suspect that creating and overriding these properties on my own could lead to unstable and/or unpredictable results.

解决方案

You can add data validation inside your SQLAlchemy classes using the @validates() decorator.

From the docs - Simple Validators:

An attribute validator can raise an exception, halting the process of mutating the attribute’s value, or can change the given value into something different.

from sqlalchemy.orm import validates

class EmailAddress(Base):
    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    email = Column(String)

    @validates('email')
    def validate_email(self, key, address):
        # you can use assertions, such as
        # assert '@' in address
        # or raise an exception:
        if '@' not in address:
            raise ValueError('Email address must contain an @ sign.')
        return address

这篇关于有没有办法透明地执行SQ​​LAlchemy对象的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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