mixins
There are certain places where heavy use of mixins can save a ton of time or cognitive load. A use case that came up recently was in a Django project where several class-based views needed to serve only traffic within our intranet. An existing middleware does this check, raising an Http404
if a request comes from outside the network. Adding that functionality to our classes was fairly easily, using decorator_from_middleware
and method_decorator
on the views’ dispatch
methods:
在某些地方,大量使用mixins可以节省大量时间或认知负担。 最近出现的一个用例是在Django项目中,在该项目中,需要几个基于类的视图来仅服务于内部网中的流量。 现有的中间件会执行此检查,如果请求来自网络外部,则会引发Http404
。 在视图的dispatch
方法上使用decorator_from_middleware
和method_decorator
可以很轻松地将该功能添加到我们的类中:
from django.views import generic
from django.views import generic
from app import middleware
@method_decorator(network_protected, name='dispatch')
@method_decorator(network_protected, name='dispatch')
class SecretView(generic.View):
class SecretView(generic.View):
...
...
However, when I added a second piece of functionality I had to decorate those views too. I was getting a little tired of decorating.
但是,当我添加第二个功能时,我也必须装饰这些视图。 我对装饰有些厌倦。
Happy Holidays
节日快乐
Instead, I refactored the network protection integration into a mixin, allowing all our class-based views to inherit from this as they saw fit:
相反,我将网络保护集成重构为一个mixin,允许我们所有基于类的视图在其认为合适的情况下从中继承:
network_protected = decorator_from_middleware(
network_protected = decorator_from_middleware(
middleware.NetworkProtectionMiddleware
middleware.NetworkProtectionMiddleware
)
)
class SecretView(NetworkProtectionMixin, generic.View):
class SecretView(NetworkProtectionMixin, generic.View):
...
...
翻译自: https://www.pybloggers.com/2016/12/mixins-for-fun-and-profit/
mixins