예제 #1
0
    def test_auto_adapt_to_methods(self):
        """
        Test that auto_adapt_to_methods actually works.
        """

        # Need 2 decorators with auto_adapt_to_methods,
        # to check it plays nicely with composing itself.

        def my_decorator(func):
            def wrapped(*args, **kwargs):
                # need to ensure that the first arg isn't 'self'
                self.assertEqual(args[0], "test")
                return "my_decorator:" + func(*args, **kwargs)

            wrapped.my_decorator_custom_attribute = True
            return wraps(func)(wrapped)

        my_decorator = auto_adapt_to_methods(my_decorator)

        def my_decorator2(func):
            def wrapped(*args, **kwargs):
                # need to ensure that the first arg isn't 'self'
                self.assertEqual(args[0], "test")
                return "my_decorator2:" + func(*args, **kwargs)

            wrapped.my_decorator2_custom_attribute = True
            return wraps(func)(wrapped)

        my_decorator2 = auto_adapt_to_methods(my_decorator2)

        class MyClass(object):
            def my_method(self, *args, **kwargs):
                return "my_method:%r %r" % (args, kwargs)

            my_method = my_decorator2(my_decorator(my_method))

        obj = MyClass()
        self.assertEqual(
            obj.my_method("test", 123, name='foo'),
            "my_decorator2:my_decorator:my_method:('test', 123) {'name': 'foo'}"
        )
        self.assertEqual(obj.my_method.__name__, 'my_method')
        self.assertEqual(
            getattr(obj.my_method, 'my_decorator_custom_attribute', False),
            True)
        self.assertEqual(
            getattr(obj.my_method, 'my_decorator2_custom_attribute', False),
            True)
예제 #2
0
def cache_control(**kwargs):
    def _cache_controller(viewfunc):
        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return auto_adapt_to_methods(_cache_controller)
예제 #3
0
파일: cache.py 프로젝트: GunioRobot/django
def cache_control(**kwargs):

    def _cache_controller(viewfunc):

        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return auto_adapt_to_methods(_cache_controller)
예제 #4
0
파일: tests.py 프로젝트: GunioRobot/django
    def test_auto_adapt_to_methods(self):
        """
        Test that auto_adapt_to_methods actually works.
        """
        # Need 2 decorators with auto_adapt_to_methods,
        # to check it plays nicely with composing itself.

        def my_decorator(func):
            def wrapped(*args, **kwargs):
                # need to ensure that the first arg isn't 'self'
                self.assertEqual(args[0], "test")
                return "my_decorator:" + func(*args, **kwargs)
            wrapped.my_decorator_custom_attribute = True
            return wraps(func)(wrapped)
        my_decorator = auto_adapt_to_methods(my_decorator)

        def my_decorator2(func):
            def wrapped(*args, **kwargs):
                # need to ensure that the first arg isn't 'self'
                self.assertEqual(args[0], "test")
                return "my_decorator2:" + func(*args, **kwargs)
            wrapped.my_decorator2_custom_attribute = True
            return wraps(func)(wrapped)
        my_decorator2 = auto_adapt_to_methods(my_decorator2)

        class MyClass(object):
            def my_method(self, *args, **kwargs):
                return "my_method:%r %r" % (args, kwargs)
            my_method = my_decorator2(my_decorator(my_method))

        obj = MyClass()
        self.assertEqual(obj.my_method("test", 123, name='foo'),
                         "my_decorator2:my_decorator:my_method:('test', 123) {'name': 'foo'}")
        self.assertEqual(obj.my_method.__name__, 'my_method')
        self.assertEqual(getattr(obj.my_method, 'my_decorator_custom_attribute', False),
                         True)
        self.assertEqual(getattr(obj.my_method, 'my_decorator2_custom_attribute', False),
                         True)
def permission_required(permission,
                        obj_lookup,
                        login_url=settings.LOGIN_URL,
                        redirect_field_name=REDIRECT_FIELD_NAME,
                        **kwargs):
    """
    Decorator for a view that makes sure that the user has *all* permissions,
    redirects to the log-in page if not logged in.
    
    :param permission: The permission set that the user must have for the object
    :type permission: An ``int``, ``string``, or ``list``
    :param obj_lookup: How to locate the object to test. It specifies the model,
                       `field and lookup <http://docs.djangoproject.com/en/dev/ref/models/querysets/#id7>`_,
                       and the name of the parameter containg the value to lookup
                       to retrieve the object
    :type obj_lookup: ``(<model>, '<field_lookup>', 'view_arg')`` or
                      ``('<appname>.<modelname>', '<field_lookup>', 'view_arg')``
    """
    if isinstance(obj_lookup, (tuple, list)):
        _model, lookup, varname = obj_lookup
    else:
        raise ValueError("The given argument '%s' should be a list or tuple" %
                         obj_lookup)

    if issubclass(_model, Model):
        model = _model
    elif isinstance(_model, basestring):
        model = get_model(*model.split("."))
    else:
        raise ValueError(
            "The model passed ('%s') is not a Model class or string in the format 'app.model'."
            % model)
    value = kwargs.get(varname, None)

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if not request.user.is_authenticated():
                path = urlquote(request.get_full_path())
                return HttpResponseRedirect(
                    '%s?%s=%s' % (login_url, redirect_field_name, path))

            obj = get_object_or_404(model, **{lookup: value})
            if request.user.has_object_permission(obj, permission):
                return view_func(request, *args, **kwargs)
            return permission_denied(request)

        return wraps(view_func)(_wrapped_view)

    return auto_adapt_to_methods(decorator)
예제 #6
0
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """
    if not login_url:
        from django.conf import settings
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = urlquote(request.get_full_path())
            tup = login_url, redirect_field_name, path
            return HttpResponseRedirect('%s?%s=%s' % tup)
        return wraps(view_func)(_wrapped_view)
    return auto_adapt_to_methods(decorator)
def permission_required(permission, obj_lookup, login_url=settings.LOGIN_URL, 
                        redirect_field_name=REDIRECT_FIELD_NAME, **kwargs):
    """
    Decorator for a view that makes sure that the user has *all* permissions,
    redirects to the log-in page if not logged in.
    
    :param permission: The permission set that the user must have for the object
    :type permission: An ``int``, ``string``, or ``list``
    :param obj_lookup: How to locate the object to test. It specifies the model,
                       `field and lookup <http://docs.djangoproject.com/en/dev/ref/models/querysets/#id7>`_,
                       and the name of the parameter containg the value to lookup
                       to retrieve the object
    :type obj_lookup: ``(<model>, '<field_lookup>', 'view_arg')`` or
                      ``('<appname>.<modelname>', '<field_lookup>', 'view_arg')``
    """
    if isinstance(obj_lookup, (tuple, list)):
        _model, lookup, varname = obj_lookup
    else:
        raise ValueError("The given argument '%s' should be a list or tuple" % obj_lookup)
    
    if issubclass(_model, Model):
        model = _model
    elif isinstance(_model, basestring):
        model = get_model(*model.split("."))
    else:
        raise ValueError("The model passed ('%s') is not a Model class or string in the format 'app.model'." % model)
    value = kwargs.get(varname, None)
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if not request.user.is_authenticated():
                path = urlquote(request.get_full_path())
                return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, path))
            
            obj = get_object_or_404(model, **{lookup: value})
            if request.user.has_object_permission(obj, permission):
                return view_func(request, *args, **kwargs)
            return permission_denied(request)
        return wraps(view_func)(_wrapped_view)
    return auto_adapt_to_methods(decorator)
    
예제 #8
0
def user_passes_test(test_func,
                     login_url=None,
                     redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """
    if not login_url:
        from django.conf import settings
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = urlquote(request.get_full_path())
            tup = login_url, redirect_field_name, path
            return HttpResponseRedirect('%s?%s=%s' % tup)

        return wraps(view_func)(_wrapped_view)

    return auto_adapt_to_methods(decorator)
예제 #9
0
파일: cache.py 프로젝트: GunioRobot/django
            return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], key_prefix=key_prefix)(args[1])
        else:
            assert False, "cache_page must be passed either a single argument (timeout) or a view function and a timeout"
    else:
        return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], key_prefix=key_prefix)

def cache_control(**kwargs):

    def _cache_controller(viewfunc):

        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return auto_adapt_to_methods(_cache_controller)

def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return wraps(view_func)(_wrapped_view_func)
never_cache = auto_adapt_to_methods(never_cache)
예제 #10
0
        return decorator_from_middleware_with_args(CacheMiddleware)(
            cache_timeout=args[0], key_prefix=key_prefix)


def cache_control(**kwargs):
    def _cache_controller(viewfunc):
        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response

        return wraps(viewfunc)(_cache_controlled)

    return auto_adapt_to_methods(_cache_controller)


def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response

    return wraps(view_func)(_wrapped_view_func)


never_cache = auto_adapt_to_methods(never_cache)