Answer the question
In order to leave comments, you need to log in
How to implement a class decorator in python?
Question for python experts.
The initial task is to wrap one of the class methods in decorators. This can be done by overriding this method and wrapping it in a method_decorator.
class MyView(View):
@method_decorator(login_required):
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
@viewdecorator(login_required)
class MyView(View):
pass
def viewdecorator(decorator):
def wrap(cls):
dispatch = getattr(cls, 'dispatch', None)
if dispatch:
setattr(cls, 'dispatch', method_decorator(decorator))
return cls
return wrap
Answer the question
In order to leave comments, you need to log in
In general, I figured it out and it turned out. If someone is interested, below is a clean code without any inheritance and an example of its use.
def viewdecorator(decorator):
def wrap(cls):
getattribute = cls.__getattribute__
def newgetattr(cls, name):
attr = getattribute(cls, name)
if name == 'dispatch':
return decorator(method_decorator(attr))
return attr
cls.__getattribute__ = newgetattr
return cls
return wrap
@viewdecorator(login_required)
@viewdecorator(csrf_exempt)
class EntriesMyList(EntriesList):
template_name = 'index.html'
class LoginRequiredMixin(View):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class ProfileUpdateView(LoginRequiredMixin, UpdateView):
...
If you understand everything correctly, then this article will help you.
Maybe you will not crutch? Are you using inheritance?
You can also wrap the login_require view in urls.py. Also a common method.
How do I decorate a function (method) inside a class?
class Example:
def func(self, f):
# что-то делает
f()
return 'decorate'
@func
def f1(self)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question