【发布时间】:2018-11-07 05:51:38
【问题描述】:
我偶然发现了一个用于为请求方法提供一些参数的代码。问题是我不确定这是否是处理这种情况的最干净的方式。
def check_permissions(check_mixins):
"""
:param check_mixins: is given to the inner decorator
Decorator that will automatically populate some parameters when
using dispatch() toward the right method (get(), post())
"""
def _decorator(_dispatch):
def wrapper(request, *args, **kwargs):
如果这里的方法定义中没有传入“self”会不会有问题...
for mixin in check_mixins:
kwargs = mixin.check(request, *args, **kwargs)
if isinstance(kwargs, HttpResponseRedirect):
return kwargs
return _dispatch(request, *args, **kwargs)
return wrapper
return _decorator
class UserLoginMixin(object):
def check(request, *args, **kwargs):
...这里呢?在我的 IDE 中看起来很丑
user = request.user
if user.is_authenticated() and not user.is_anonymous():
kwargs['user'] = user
return kwargs
return redirect('user_login')
class AppoExistMixin(object):
def check(request, *args, **kwargs):
这里也是……
appo_id = kwargs['appo_id']
try:
appoff = IdAppoff.objects.get(id=appo_id)
kwargs['appoff'] = appoff
del kwargs['appo_id']
return kwargs
except IdAppoff.DoesNotExist:
pass
messages.add_message(request, messages.ERROR,
"Item doesn't exist!")
return redirect('home')
class SecurityMixin(View):
"""
Mixin that dispatch() to the right method with augmented kwargs.
kwargs are added if they match to specific treatment.
"""
data = []
def __init__(self, authenticators):
super(SecurityMixin, self).__init__()
# Clearing data in order to not add useless param to kwargs
self.data.clear()
# Build the list that contain each authenticator providing
# context increase
for auth in authenticators:
self.data.append(auth)
@method_decorator(check_permissions(data))
为什么是 data 而不是 self.data ?怎么可能?
def dispatch(self, request, *args, **kwargs):
return super(SecurityMixin, self).dispatch(request, *args, **kwargs)
然后每个视图都继承自 SecurityMixin 并获得authenticators = [UserLoginMixin, ...] 作为类属性。
有时的问题(我无法重现错误...)是在正确设置 URL 定义时,我在增强的 kwargs 上遇到了 KeyError。例如:
appo_id = kwargs['appo_id']
KeyError: 'appo_id'Exception
我已经找了好几个小时了,但似乎我永远也找不到解决方案……这有点令人沮丧。
如果有人可以提供帮助,将不胜感激。
【问题讨论】: