【发布时间】:2019-02-15 05:22:51
【问题描述】:
我正在为 Django REST API 实现内容感知缓存系统。我想开发一个组件,它可以添加到现有视图中,通过检查缓存并在未命中时回退到基类行为来修改基类的行为。
基本上,我有这样的事情:
class Base:
def get(self, request, *args, **kwargs):
....
return Response
class AnotherBase:
def get(self, request, *args, **kwargs):
....
return Response
class Derived(Base):
pass
class OtherDerived(AnotherBase):
pass
我最初的想法是按照
class Cacheable:
def get(self, request, *args, **kwargs):
cache_key = self.get_cache_key(request)
base_get = #.... and this is the problem
return cache.get(cache_key, base_get(request, *args, **kwargs))
def get_cache_key(self, request):
# .... do stuff
class Derived(Cacheable, Base):
pass
class AnotherDerived(Cacheable, AnotherBase):
pass
很明显这不起作用,因为我不知道如何,或者是否可能,或者是否建议从 mixin 访问兄弟超类。
我的目标是一个实现,它允许我向现有视图添加缓存行为,而无需触及现有类的内部。
给定一个视图类,C,s.t. C.get(request, *args, **kwargs) -> Response,有没有函数,F,s.t. F(C).get(... 在回退到 C.get 之前是否会检查缓存?在这个准正式的符号中,我们会说在类定义中向最左边的父类添加一个 mixin 算作一个函数。
使用方法装饰器是否更合适?或者类装饰器如何工作?
然后我在研究这个时看到了对__metaclass__ 的引用,但我不清楚这种方法是什么样的。
这是 Python 3.6
【问题讨论】:
-
我认为问题的一部分也是
cache.get(cache_key, base_get(request, *args, **kwargs))。您正在不必要地计算基本获取。
标签: python django metaprogramming multiple-inheritance python-decorators