我有一个使用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函数,并使用了清理后的数据 . 万岁 .
我当然可以停在那里,只是吃掉了对列的丑陋处理,但为什么当你可以搞乱元类时呢?
Note :以下都假定'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)
这几乎可以工作,因为's no errors, data is read and saved correctly, etc. Except the setter for the hybrid_property is never called. The getter is (I'已经确认了两者中的打印语句,但是完全忽略了setter,因此从不调用更干净的函数 . 虽然设置了数据 - 使用未清理的数据可以非常愉快地进行更改 .
显然我还没有在我的动态版本中完全模拟代码的静态版本,但老实说我不知道问题出在哪里 . 就我所知,hybrid_property应该像注册器一样注册setter,但事实并非如此 . 在静态版本中,setter已注册并使用得很好 .
关于如何使最后一步工作的任何想法?
1 回答
也许使用自定义类型?
然后你可以这样写你的模型:
此处的文档中提供了更多说明:http://docs.sqlalchemy.org/en/latest/core/custom_types.html#augmenting-existing-types