Python 从类到日志ORM访问修饰静态方法
所以我有以下问题。我正在构建一个flask应用程序,后台是mongoDB数据库。现在,我想记录对数据存储中任何模型的所有更改。因此,我开始为我的数据库模型类开发一些注释。然而,我正在努力正确地装饰Python 从类到日志ORM访问修饰静态方法,python,python-3.x,flask,orm,decorator,Python,Python 3.x,Flask,Orm,Decorator,所以我有以下问题。我正在构建一个flask应用程序,后台是mongoDB数据库。现在,我想记录对数据存储中任何模型的所有更改。因此,我开始为我的数据库模型类开发一些注释。然而,我正在努力正确地装饰mongoengine.Document的静态方法 我有一个条目类,看起来像这样: from somewhere import db from Logger import EntitiesLogger @EntitiesLogger class Entry(db.Document): text
mongoengine.Document
的静态方法
我有一个条目
类,看起来像这样:
from somewhere import db
from Logger import EntitiesLogger
@EntitiesLogger
class Entry(db.Document):
text = db.StringField()
resource = db.ReferenceField(Resource)
meta = {'allow_inheritance': True)
我的decorator类如下所示(为了调试目的,我添加了一些打印):
我现在可以很容易地调用entry=entry(…)
,装饰器就可以工作了。当我访问db.document
类的函数,如entry.save()
时,这同样有效。只有当我访问db.document
的描述符,或者更具体地说,我的Entry
类,比如Entry.objects(field='something')
时,我才会遇到问题。不知何故,我需要将对诸如.objects(…)
之类的静态方法的调用转发给修饰类,但即使实现\uuuuu get\uuuu(…)
,这也永远不会起作用。我总是收到属性错误:类型对象“NewCls”没有属性“objects”
。有人知道如何正确地实现这个装饰器来将所有调用转发给装饰类吗
提前多谢 您必须使用元类来拦截类属性查找,但为什么不在decorator中更改类而不是创建代理?您必须使用元类来拦截类属性查找,但为什么不在decorator中更改类而不是创建代理?
def EntitiesLogger(Cls):
class NewCls(object):
def __init__(self, *args, **kwargs):
self.oInstance = Cls(*args, **kwargs)
def __getattribute__(self, attr):
try:
x = super(NewCls, self).__getattribute__(attr)
except AttributeError:
print('ERROR')
else:
return x
x = self.oInstance.__getattribute__(attr)
if type(x) == type(self.__init__):
print('Data changed')
return x
else:
return x
def __get__(self, instance, owner):
print('static method called')
return NewCls