我有一个使用SQLAlchemy的现有工作Flask应用程序。这个应用程序中的几个模型/表具有存储原始HTML的列,我想在列的setter上注入一个函数,以便传入的原始html被“清理”。我想在模型中执行此操作,因此我不必通过表单或路径代码来“清理此数据”。
我现在可以这样做了:
from application import db, clean_the_data
from sqlalchemy.ext.hybrid import hybrid_property
class Example(db.Model):
__tablename__ = 'example'
normal_column = db.Column(db.Integer,
primary_key=True,
autoincrement=True)
_html_column = db.Column('html_column', db.Text,
nullable=False)
@hybrid_property
def html_column(self):
return self._html_column
@html_column.setter
def html_column(self, value):
self._html_column = clean_the_data(value)
这就像一个魅力 - 除了模型定义之外,从未看到_html_column名称,调用了clean函数,并使用了清理后的数据。万岁。
我当然可以停在那里,只是吃掉了对列的丑陋处理,但是为什么在你可以搞乱元类时呢?
注意:以下都假定'application'是主要的Flask模块,它包含两个子节点:'db' - SQLAlchemy句柄和'clean_the_data',清理函数传入的HTML。
所以,我开始尝试创建一个新的基类Model类,它在创建类时发现需要清理的列,并自动处理周围的事情,这样代替上面的代码,你可以做这样的事情:
from application import db
class Example(db.Model):
__tablename__ = 'example'
__html_columns__ = ['html_column'] # Our oh-so-subtle hint
normal_column = db.Column(db.Integer,
primary_key=True,
autoincrement=True)
html_column = db.Column(db.Text,
nullable=False)
当然,使用SQLAlchemy和Flask在幕后进行的技巧与元类的组合使得这不是直接的(并且也是为什么几乎匹配的问题“在SQLAlchemy中创建混合属性的自定义元类”不会非常有帮助 - Flask也阻碍了它。我几乎已经在application / models / __ init __。py:
中得到了以下内容from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
# Yes, I'm importing _X stuff...I tried other ways to avoid this
# but to no avail
from flask_sqlalchemy import (Model as BaseModel,
_BoundDeclarativeMeta,
_QueryProperty)
from application import db, clean_the_data
class _HTMLBoundDeclarativeMeta(_BoundDeclarativeMeta):
def __new__(cls, name, bases, d):
# Move any fields named in __html_columns__ to a
# _field/field pair with a hybrid_property
if '__html_columns__' in d:
for field in d['__html_columns__']:
if field not in d:
continue
hidden = '_' + field
fget = lambda self: getattr(self, hidden)
fset = lambda self, value: setattr(self, hidden,
clean_the_data(value))
d[hidden] = d[field] # clobber...
d[hidden].name = field # So we don't have to explicitly
# name the column. Should probably
# force a quote on the name too
d[field] = hybrid_property(fget, fset)
del d['__html_columns__'] # Not needed any more
return _BoundDeclarativeMeta.__new__(cls, name, bases, d)
# The following copied from how flask_sqlalchemy creates it's Model
Model = declarative_base(cls=BaseModel, name='Model',
metaclass=_HTMLBoundDeclarativeMeta)
Model.query = _QueryProperty(db)
# Need to replace the original Model in flask_sqlalchemy, otherwise it
# uses the old one, while you use the new one, and tables aren't
# shared between them
db.Model = Model
设置完成后,您的模型类可能如下所示:
from application import db
from application.models import Model
class Example(Model): # Or db.Model really, since it's been replaced
__tablename__ = 'example'
__html_columns__ = ['html_column'] # Our oh-so-subtle hint
normal_column = db.Column(db.Integer,
primary_key=True,
autoincrement=True)
html_column = db.Column(db.Text,
nullable=False)
这个几乎有效,因为没有错误,数据被正确读取和保存等等。除了从不调用hybrid_property的setter。 getter是(我在两者中都确认了print语句),但是setter被完全忽略,因此从不调用更干净的函数。设置了数据 - 使用未清理的数据非常愉快地进行了更改。
显然我还没有完全模仿我的动态版本中的静态版本代码,但老实说我不知道问题出在哪里。就我所见,hybrid_property 应注册setter就像它有getter一样,但事实并非如此。在静态版本中,setter被注册并使用得很好。
关于如何使最后一步有效的任何想法?
答案 0 :(得分:4)
也许使用自定义类型?
from sqlalchemy import TypeDecorator, Text
class CleanedHtml(TypeDecorator):
impl = Text
def process_bind_param(self, value, dialect):
return clean_the_data(value)
然后你可以这样写你的模型:
class Example(db.Model):
__tablename__ = 'example'
normal_column = db.Column(db.Integer, primary_key=True, autoincrement=True)
html_column = db.Column(CleanedHtml)
此处的文档中提供了更多说明:http://docs.sqlalchemy.org/en/latest/core/custom_types.html#augmenting-existing-types