Python 一般为所有字符串字段剥离空白-SQLAlchemy

Python 一般为所有字符串字段剥离空白-SQLAlchemy,python,orm,sqlalchemy,flask-sqlalchemy,string-parsing,Python,Orm,Sqlalchemy,Flask Sqlalchemy,String Parsing,我通过SQLAlchemy将SQLAlchemy用作web应用程序的ORM 我希望在分配给任何字符串字段时自动前导和尾随带空格(例如,str.strip) 执行此操作的一种方法如下,但需要为每个字符串字段指定: class User(db.Model): _email = db.Column('email', db.String(100), primary_key=True) @hybrid_property def email(self): return self._e

我通过SQLAlchemy将SQLAlchemy用作web应用程序的ORM

我希望在分配给任何字符串字段时自动前导和尾随带空格(例如,
str.strip

执行此操作的一种方法如下,但需要为每个字符串字段指定:

class User(db.Model):
    _email = db.Column('email', db.String(100), primary_key=True)
    @hybrid_property
    def email(self): return self._email
    @email.setter
    def email(self, data): self._email = data.strip()

我希望对每个字符串字段更一般地这样做(而不必为每个字段编写上述内容)

一种方法是创建处理此类处理的自定义:

from sqlalchemy.types import TypeDecorator

class StrippedString(TypeDecorator):

    impl = db.String

    def process_bind_param(self, value, dialect):
        # In case you have nullable string fields and pass None
        return value.strip() if value else value

    def copy(self, **kw):
        return StrippedString(self.impl.length)
然后,在您的模型中,您将使用此字符串来代替普通的
字符串

class User(db.Model):
    email = db.Column(StrippedString(100), primary_key=True)
这与您自己的实现并不完全相同,因为处理是在值作为参数绑定到查询时进行的,或者稍后进行:

In [12]: u = User(email='     so.much@white.space     ')

In [13]: u.email
Out[13]: '     so.much@white.space     '

In [14]: session.add(u)

In [15]: session.commit()

In [16]: u.email
Out[16]: 'so.much@white.space'

一种方法是创建处理此类处理的自定义:

from sqlalchemy.types import TypeDecorator

class StrippedString(TypeDecorator):

    impl = db.String

    def process_bind_param(self, value, dialect):
        # In case you have nullable string fields and pass None
        return value.strip() if value else value

    def copy(self, **kw):
        return StrippedString(self.impl.length)
然后,在您的模型中,您将使用此字符串来代替普通的
字符串

class User(db.Model):
    email = db.Column(StrippedString(100), primary_key=True)
这与您自己的实现并不完全相同,因为处理是在值作为参数绑定到查询时进行的,或者稍后进行:

In [12]: u = User(email='     so.much@white.space     ')

In [13]: u.email
Out[13]: '     so.much@white.space     '

In [14]: session.add(u)

In [15]: session.commit()

In [16]: u.email
Out[16]: 'so.much@white.space'
相关,但相关的“镜子”,但相关的“镜子”