Python django.utils.decorators.method_decorator() Examples
The following are 30
code examples of django.utils.decorators.method_decorator().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.decorators
, or try the search function
.
Example #1
Source File: views.py From django-datatables-view with MIT License | 7 votes |
def fix_initial_order(self, initial_order): """ "initial_order" is a list of (position, direction) tuples; for example: [[1, 'asc'], [5, 'desc']] Here, we also accept positions expressed as column names, and convert the to the corresponding numeric position. """ values = [] keys = list(self.column_index.keys()) for position, direction in initial_order: if type(position) == str: position = keys.index(position) values.append([position, direction]) return values #@method_decorator(csrf_exempt)
Example #2
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests"
Example #3
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments.
Example #4
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests"
Example #5
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments.
Example #6
Source File: decorators.py From sal with Apache License 2.0 | 6 votes |
def class_access_required(cls): """Decorator for View subclasses to restrict by business unit. Class must declare a classmethod `get_business_unit` that returns the BusinessUnit object that applies to the query in question. Args: cls: Class to decorate. Returns: Decorated class. Raises: 403 Pemission Denied if current user does not have access. 404 if requested group doesn't exist. """ def access_required(function): def decorator(*args, **kwargs): # The request object is the first arg to a view request = args[0] user = request.user business_unit = cls.get_business_unit(**kwargs) if has_access(user, business_unit): return function(*args, **kwargs) else: raise PermissionDenied() return decorator access_decorator = method_decorator(access_required) cls.dispatch = access_decorator(cls.dispatch) return cls
Example #7
Source File: views.py From Python24 with MIT License | 6 votes |
def check_ip(func): # 实现禁止ip黑名单访问发帖界面。 解决: 可以通过在视图函数中使用装饰器实现 def wrapper(request, *args, **kwargs): # 在视图函数执行前做额外的操作: # 禁止ip黑名单访问 IP = request.META.get('REMOTE_ADDR') if IP not in ['192.168.210.160']: return HttpResponse('IP禁止访问') # 一切正常,返回该返回的 return func(request, *args, **kwargs) return wrapper # 方式4, 直接把装饰器定义成适合类视图函数的装饰器,添加一个self参数,这样就能直接在类视图函数中不需要method_decorator了
Example #8
Source File: middleware.py From django-defender with Apache License 2.0 | 6 votes |
def __init__(self, *args, **kwargs): super(FailedLoginMiddleware, self).__init__(*args, **kwargs) # Watch the auth login. # Monkey-patch only once - otherwise we would be recording # failed attempts multiple times! if not FailedLoginMiddleware.patched: # Django 1.11 turned the `login` function view into the # `LoginView` class-based view try: from django.contrib.auth.views import LoginView our_decorator = watch_login() watch_login_method = method_decorator(our_decorator) LoginView.dispatch = watch_login_method(LoginView.dispatch) except ImportError: # Django < 1.11 auth_views.login = watch_login()(auth_views.login) FailedLoginMiddleware.patched = True
Example #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator
Example #10
Source File: mobile_survey.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def notify_mobile_survey_end(self, request, mobile_survey): admin_email = settings.ADMINS[0][1] if settings.ADMINS else "" email_context = { "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)), "link": request.build_absolute_uri(reverse("home")), "greeting": _( "Hi! The Mobile Survey you were part of has ended or is temporarily suspended. \ Please permform a final sync of your local dataset as soon as possible." ), "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."), } html_content = render_to_string("email/general_notification.htm", email_context) text_content = strip_tags(html_content) # this strips the html, so people will have the text as well. # create the email, and attach the HTML version as well. for user in self.get_mobile_survey_users(mobile_survey): msg = EmailMultiAlternatives( _("There's been a change to an {app_name} Survey that you're part of!".format(app_name=settings.APP_NAME)), text_content, admin_email, [user.email], ) msg.attach_alternative(html_content, "text/html") msg.send() # @method_decorator(can_read_resource_instance(), name='dispatch')
Example #11
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!")
Example #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method())
Example #13
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1)
Example #14
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False)
Example #15
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True)
Example #16
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_queryset(self, **kwargs): name = self.request.GET.get('name', '') return Disease.objects.filter(Q(name__icontains=name)|Q(gene_names__icontains=name)) # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(DiseaseListView, self).dispatch(*args, **kwargs)
Example #17
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name='nonexistent_method') class Test: @classmethod def __module__(cls): return "tests"
Example #18
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_queryset(self, **kwargs): name = self.request.GET.get('name', '') return Disease.objects.filter(Q(name__icontains=name)|Q(gene_names__icontains=name)) # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(DiseaseListView, self).dispatch(*args, **kwargs)
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!")
Example #20
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1)
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False)
Example #22
Source File: views.py From Python24 with MIT License | 5 votes |
def as_view(cls, *args, **kwargs): view = super().as_view(*args, **kwargs) # 在这里添加自己的装饰器 view = check_ip(view) return view # 方式3, name=dispatch的话就是给所有的函数添加装饰器 # @method_decorator(check_ip, name='get') # @method_decorator(check_ip, name='dispatch')
Example #23
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True)
Example #24
Source File: views.py From mendelmd with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_queryset(self, **kwargs): name = self.request.GET.get('name', '') return Disease.objects.filter(Q(name__icontains=name)|Q(gene_names__icontains=name)) # @method_decorator(login_required) # def dispatch(self, *args, **kwargs): # return super(DiseaseListView, self).dispatch(*args, **kwargs)
Example #25
Source File: decorators.py From sal with Apache License 2.0 | 5 votes |
def class_staff_required(cls): """Class decorator for View subclasses to restrict to staff.""" decorator = method_decorator(staff_required) cls.dispatch = decorator(cls.dispatch) return cls
Example #26
Source File: decorators.py From sal with Apache License 2.0 | 5 votes |
def class_ga_required(cls): """Class decorator for View subclasses to restrict to GA.""" decorator = method_decorator(ga_required) cls.dispatch = decorator(cls.dispatch) return cls
Example #27
Source File: decorators.py From sal with Apache License 2.0 | 5 votes |
def class_login_required(cls): """Class decorator for View subclasses to restrict to logged in.""" decorator = method_decorator(login_required) cls.dispatch = decorator(cls.dispatch) return cls
Example #28
Source File: views.py From vortessence with GNU General Public License v2.0 | 5 votes |
def class_view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. """ def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return simple_decorator
Example #29
Source File: views.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def class_view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. """ def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return simple_decorator
Example #30
Source File: utilities.py From django-carrot with Apache License 2.0 | 5 votes |
def get_mixin(decorator: Callable) -> Type[object]: """ Helper function that allows dynamic application of decorators to a class-based views :param func decorator: the decorator to apply to the view """ class Mixin(object): @method_decorator(decorator) def dispatch(self, request, *args, **kwargs): return super(Mixin, self).dispatch(request, *args, **kwargs) return Mixin