python-Flask SQLAlchemy-修改列设置器的自定义元类(动态hybrid_property)
作者:互联网
我有一个使用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函数,并使用了cleaned数据.万岁.
我当然可以停在那里,只吃掉对列的丑陋处理,但是当您可以弄乱元类时为什么要这么做呢?
注意:以下全部假设’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中使用自定义元类创建混合属性”并没有太大帮助-烧瓶也会挡住).我几乎已经在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的设置程序之外. getter是(我已经在两个声明中都确认了),但是setter被完全忽略了,因此永远不会调用cleaner函数.尽管已设置数据-使用未清除的数据可以很愉快地进行更改.
显然,我还没有完全在动态版本中模拟静态代码版本,但是老实说,我不知道问题出在哪里.据我所知,hybrid_property应该像使用getter一样注册setter,但事实并非如此.在静态版本中,setter已注册并可以正常使用.
关于如何使最后一步起作用的任何想法?
解决方法:
也许使用自定义类型?
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
标签:sqlalchemy,flask,flask-sqlalchemy,metaclass,python 来源: https://codeday.me/bug/20191028/1952949.html