mixins_Mixins带来乐趣和利润

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_middlewaremethod_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值