Exemplo n.º 1
0
def cache_page(*args, **kwargs):
    # We need backwards compatibility with code which spells it this way:
    #   def my_view(): pass
    #   my_view = cache_page(my_view, 123)
    # and this way:
    #   my_view = cache_page(123)(my_view)
    # and this:
    #   my_view = cache_page(my_view, 123, key_prefix="foo")
    # and this:
    #   my_view = cache_page(123, key_prefix="foo")(my_view)
    # and possibly this way (?):
    #   my_view = cache_page(123, my_view)

    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    key_prefix = kwargs.pop('key_prefix', None)
    assert not kwargs, "The only keyword argument accepted is key_prefix"
    if len(args) > 1:
        assert len(args) == 2, "cache_page accepts at most 2 arguments"
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[1], key_prefix=key_prefix)(args[0])
        elif callable(args[1]):
            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)
Exemplo n.º 2
0
def cache_page(*args, **kwargs):
    # We need backwards compatibility with code which spells it this way:
    #   def my_view(): pass
    #   my_view = cache_page(my_view, 123)
    # and this way:
    #   my_view = cache_page(123)(my_view)
    # and this:
    #   my_view = cache_page(my_view, 123, key_prefix="foo")
    # and this:
    #   my_view = cache_page(123, key_prefix="foo")(my_view)
    # and possibly this way (?):
    #   my_view = cache_page(123, my_view)

    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    key_prefix = kwargs.pop('key_prefix', None)
    assert not kwargs, "The only keyword argument accepted is key_prefix"
    if len(args) > 1:
        assert len(args) == 2, "cache_page accepts at most 2 arguments"
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[1], key_prefix=key_prefix)(args[0])
        elif callable(args[1]):
            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)
Exemplo n.º 3
0
def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    sites.get_current().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We need backwards compatibility with code which spells it this way:
    #   def my_view(): pass
    #   my_view = cache_page(my_view, 123)
    # and this way:
    #   my_view = cache_page(123)(my_view)
    # and this:
    #   my_view = cache_page(my_view, 123, key_prefix="foo")
    # and this:
    #   my_view = cache_page(123, key_prefix="foo")(my_view)
    # and possibly this way (?):
    #   my_view = cache_page(123, my_view)
    # and also this way:
    #   my_view = cache_page(my_view)
    # and also this way:
    #   my_view = cache_page()(my_view)

    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    cache_alias = kwargs.pop("cache", None)
    key_prefix = kwargs.pop("key_prefix", None)
    assert not kwargs, "The only keyword arguments are cache and key_prefix"
    if len(args) > 1:
        assert len(args) == 2, "cache_page accepts at most 2 arguments"
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[1], cache_alias=cache_alias, key_prefix=key_prefix
            )(args[0])
        elif callable(args[1]):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix
            )(args[1])
        else:
            assert False, "cache_page must be passed a view function if called with two arguments"
    elif len(args) == 1:
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)(
                args[0]
            )
        else:
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix
            )
    else:
        return decorator_from_middleware_with_args(CacheMiddleware)(cache_alias=cache_alias, key_prefix=key_prefix)
Exemplo n.º 4
0
def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    sites.get_current().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We need backwards compatibility with code which spells it this way:
    #   def my_view(): pass
    #   my_view = cache_page(my_view, 123)
    # and this way:
    #   my_view = cache_page(123)(my_view)
    # and this:
    #   my_view = cache_page(my_view, 123, key_prefix="foo")
    # and this:
    #   my_view = cache_page(123, key_prefix="foo")(my_view)
    # and possibly this way (?):
    #   my_view = cache_page(123, my_view)
    # and also this way:
    #   my_view = cache_page(my_view)
    # and also this way:
    #   my_view = cache_page()(my_view)

    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    key_prefix = kwargs.pop('key_prefix', None)
    assert not kwargs, "The only keyword argument accepted is key_prefix"
    if len(args) > 1:
        assert len(args) == 2, "cache_page accepts at most 2 arguments"
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[1], key_prefix=key_prefix)(args[0])
        elif callable(args[1]):
            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 a view function if called with two arguments"
    elif len(args) == 1:
        if callable(args[0]):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                key_prefix=key_prefix)(args[0])
        else:
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[0], key_prefix=key_prefix)
    else:
        return decorator_from_middleware_with_args(CacheMiddleware)(
            key_prefix=key_prefix)
Exemplo n.º 5
0
def cache_page_nginx(view_fn=None, cache_timeout=settings.CACHE_NGINX_TIME,
                     anonymous_only=False):
    decorator = decorator_from_middleware_with_args(UpdateCacheMiddleware)(
        cache_timeout=cache_timeout, anonymous_only=anonymous_only)
    if callable(view_fn):
        return decorator(view_fn)
    return decorator
Exemplo n.º 6
0
def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError(
            "cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError(
            "cache_page has two optional keyword arguments: cache and key_prefix"
        )

    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout,
        cache_alias=cache_alias,
        key_prefix=key_prefix)
Exemplo n.º 7
0
def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError("cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
    )
    def test_daily_cache(self, patched_date):
        """Cache should be consistent within a day but not between days"""
        fn = Mock(return_value=HttpResponse('response'))
        request = RequestFactory().get('a-path')

        mock_caches = {
            'example': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
            }
        }
        with self.settings(CACHES=mock_caches):
            daily_cache = decorator_from_middleware_with_args(
                url_caches.DailyCacheMiddleware)(cache_alias='example')
            wrapped_fn = daily_cache(fn)

        patched_date.today.return_value = date(2010, 10, 10)
        self.assertEqual(fn.call_count, 0)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 1)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 1)

        patched_date.today.return_value = date(2010, 10, 11)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 2)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 2)
Exemplo n.º 9
0
def lockdown(*args, **kwargs):
    """Define a decorator based on the LockdownMiddleware.

    This decorator takes the same arguments as the middleware, but allows a
    more granular locking than the middleware.
    """
    return decorator_from_middleware_with_args(LockdownMiddleware)(*args,
                                                                   **kwargs)
Exemplo n.º 10
0
def cache_page_nginx(view_fn=None,
                     cache_timeout=settings.CACHE_NGINX_TIME,
                     anonymous_only=False):
    decorator = decorator_from_middleware_with_args(UpdateCacheMiddleware)(
        cache_timeout=cache_timeout, anonymous_only=anonymous_only)
    if callable(view_fn):
        return decorator(view_fn)
    return decorator
    def decorator_func(func):
        params_validator = decorator_from_middleware_with_args(
            RequestBodyValidatorMiddleware)

        @params_validator(json_schema)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)

        return wrapper
Exemplo n.º 12
0
def cache_page_anonymous(*args, **kwargs):
    """
    Decorator to cache Django views only for anonymous users.
    Use just like the decorator cache_page:

    @cache_page_anonymous(60 * 30)  # cache for 30 mins
    def your_view_here(request):
        ...
    """
    key_prefix = kwargs.pop('key_prefix', None)
    return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], 
                                                                key_prefix=key_prefix, 
                                                                cache_anonymous_only=True)
Exemplo n.º 13
0
    def cache_page_against_model_decorator(func):
        # Retrieve django-style view name from view func
        view_name = get_view_name(func)

        # Map the view keywords to model fields using the to_fields group
        if callable(to_fields):
            raise ValueError(
                'to_fields is a specialized group that cannot be a callable')

        if to_fields is None:
            # If to_fields is not given, we have no choice but getting the
            # keywords by inspecting the view. Convenient, but less than
            # ideal, as it means that *args, **kwargs style views signature
            # will not get properly detected -- this is what might happens
            # with views having cascading decorators.
            modelfields = inspect.getargspec(func)[0][1:]
        else:
            # Other sequences and mappings only needs to be saved, as it's
            # assumed there is a perfect relationship to model fields.
            modelfields = list(to_fields)

        if len(modelfields) == 0:
            raise ValueError(
                'there is no field left to match model entities against: '
                'if all you are interested in is invalidating all pages '
                'associated with a given view whenever an entity '
                'from a given model is changed, use '
                'the cache_page_for_models() decorator instead')

        def invalidate(sender, instance, signal, *args, **kwargs):
            # Construct the mapping from model instance
            mapping = dict(
                (field, getattr(instance, field)) for field in modelfields)

            # Get the corresponding local key, and bump it.
            local_key = get_local_key_from_mapping(mapping, view_name)
            print 'local key', local_key
            bump_local_prefix(local_key)
            print 'Invalidating:', instance, signal, args, kwargs

        post_save.connect(invalidate,
                          sender=model,
                          weak=False,
                          dispatch_uid=view_name)

        return decorator_from_middleware_with_args(
            CacheWithLocalVersionMiddleware)(cache_timeout=cache_timeout,
                                             group=to_fields,
                                             view_func=func,
                                             vary_on_view=True)(func)
Exemplo n.º 14
0
def cache_page(**kwargs):
    """
    This decorator is similar to `django.views.decorators.cache.cache_page`
    """
    cache_timeout = kwargs.pop('cache_timeout', None)
    key_prefix = kwargs.pop('key_prefix', None)
    cache_min_age = kwargs.pop('cache_min_age', None)
    decorator = decorators.decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout,
        key_prefix=key_prefix,
        cache_min_age=cache_min_age,
        **kwargs
    )
    return decorator
Exemplo n.º 15
0
def cache_page_if_anonymous(timeout, *, cache=None, key_prefix=None):
    """
    Decorator that behaves like django's cache_page(), but only for anonymous
    users.
    """
    class _CacheMiddlewareIfAnonymous(CacheMiddleware):
        def process_request(self, request):
            if request.user.is_authenticated:
                request._cache_update_cache = False
                return None
            return super().process_request(request)

    return decorator_from_middleware_with_args(_CacheMiddlewareIfAnonymous)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix)
Exemplo n.º 16
0
def cache_page_nginx(view_fn=None,
                     cache_timeout=settings.CACHE_NGINX_TIME,
                     page_version_fn=None,
                     anonymous_only=False,
                     lookup_identifier=None,
                     supplementary_identifier=None):
    decorator = decorator_from_middleware_with_args(UpdateCacheMiddleware)(
        cache_timeout=cache_timeout,
        page_version_fn=page_version_fn,
        anonymous_only=anonymous_only,
        lookup_identifier=lookup_identifier,
        supplementary_identifier=supplementary_identifier)
    if callable(view_fn):
        return decorator(view_fn)
    return decorator
Exemplo n.º 17
0
def cache_page_anonymous(*args, **kwargs):
    """
  Taken from: http://djangosnippets.org/snippets/2230/ .
  Decorator to cache Django views only for anonymous users.
  Use just like the decorator cache_page:

  @cache_page_anonymous(60 * 30)  # cache for 30 mins
  def your_view_here(request):
    ...
  """
    key_prefix = kwargs.pop('key_prefix', None)
    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=args[0],
        key_prefix=key_prefix,
        cache_anonymous_only=True)
Exemplo n.º 18
0
def cache_page(timeout, *, cache=None, key_prefix=None):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix)
Exemplo n.º 19
0
def cache_page(timeout, *, cache=None, key_prefix=None):
    """
    用于尝试从缓存中获取页面的视图的装饰器
    如果页面尚未在缓存中,则填充缓存。

    缓存的键 由URL和标头中的一些数据生成。
    此外,还有用于区分不同的键前缀
    缓存多站点设置中的区域。 你可以使用
    get_current_site域,例如,因为它在Django中是唯一的
    项目。

    此外,将采用响应的Vary标头中的所有标头考虑缓存 - 就像中间件一样。
    不同的请求头缓存不一样
    """
    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix)
Exemplo n.º 20
0
def cache_page(timeout, *, cache=None, key_prefix=None):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix
    )
Exemplo n.º 21
0
def _cache_page(*args, **kwargs):
    """
    Copied almost everything from the original except replacing the middleware.
    """
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError("cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

    return decorator_from_middleware_with_args(ResilientCacheMiddleware)(cache_timeout=cache_timeout,
                                                                         cache_alias=cache_alias,
                                                                         key_prefix=key_prefix)
Exemplo n.º 22
0
def cache_page_nginx(
        view_fn=None,
        cache_timeout=settings.CACHE_NGINX_TIME,
        page_version_fn=None,
        anonymous_only=False,
        lookup_identifier=None,
        supplementary_identifier=None
    ):
    decorator = decorator_from_middleware_with_args(UpdateCacheMiddleware)(
        cache_timeout=cache_timeout,
        page_version_fn=page_version_fn,
        anonymous_only=anonymous_only,
        lookup_identifier=lookup_identifier,
        supplementary_identifier=supplementary_identifier
    )
    if callable(view_fn):
        return decorator(view_fn)
    return decorator
Exemplo n.º 23
0
def gcframe(compat_mode=IE_COMPATIBILITY_MODE, act_method=IE_ACTIVATION_METHOD):
    """
    Decorator that adds ``X-UA-Compatible`` header to a view function.

    E.g.::

        @gcframe()
        def some_view(request):
            ...

    Optionally accepts ``compat_mode`` and ``act_method`` arguments. See
    the documentation for how these modify behavior.

    If GoogleChromeFrameIEMiddleware is installed, the arguments given
    to this decorator will take precedence.

    """

    return decorator_from_middleware_with_args(GoogleChromeFrameIEMiddleware)(compat_mode=compat_mode, act_method=act_method)
Exemplo n.º 24
0
    def cache_page_against_models_decorator(func):
        view_name = get_view_name(func)

        def invalidate(sender, instance, signal, *args, **kwargs):
            bump_local_prefix(get_local_key_from_mapping({}, view_name))

        for model in models:
            for sig in (post_save, post_delete):
                sig.connect(invalidate,
                            sender=model,
                            weak=False,
                            dispatch_uid=view_name)

        return decorator_from_middleware_with_args(
            CacheWithLocalVersionMiddleware)(
                cache_timeout=kwargs.get('cache_timeout'),
                group=(),
                view_func=func,
                vary_on_view=True)(func)
Exemplo n.º 25
0
    def test_daily_cache(self, patched_date):
        """Cache should be consistent within a day but not between days"""
        fn = Mock(return_value=HttpResponse('response'))
        request = RequestFactory().get('a-path')

        mock_caches = {'example': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
        with self.settings(CACHES=mock_caches):
            daily_cache = decorator_from_middleware_with_args(
                url_caches.DailyCacheMiddleware)(cache_alias='example')
            wrapped_fn = daily_cache(fn)

        patched_date.today.return_value = date(2010, 10, 10)
        self.assertEqual(fn.call_count, 0)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 1)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 1)

        patched_date.today.return_value = date(2010, 10, 11)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 2)
        wrapped_fn(request)
        self.assertEqual(fn.call_count, 2)
Exemplo n.º 26
0
    # default templates.

    @es_required_or_50x()
    def home_view(request):
        ...


    # This creates a search_view and overrides the templates

    @es_required_or_50x(disabled_template='search/es_disabled.html',
                        error_template('search/es_down.html')
    def search_view(request):
        ...

"""
es_required_or_50x = decorator_from_middleware_with_args(ESExceptionMiddleware)


class S(elasticutils.S):
    """S that's more Django-focused

    * creates ElasticSearch objects based on ``settings.py`` settings

    """
    def __init__(self, mapping_type):
        """Create and return an S.

        :arg mapping_type: class; the mapping type that this S is based on

        .. Note::
Exemplo n.º 27
0
from django.utils.decorators import decorator_from_middleware_with_args
from lockdown.middleware import LockdownMiddleware

lockdown = decorator_from_middleware_with_args(LockdownMiddleware)
Exemplo n.º 28
0
def cache_page(cache_timeout, get_key_prefix=None):
    return decorator_from_middleware_with_args(
        DynamicKeyPrefixCacheMiddleware)(cache_timeout=cache_timeout,
                                         get_key_prefix=get_key_prefix)
Exemplo n.º 29
0
def cache_page(timeout, cache=None, key_prefix=None):
    return decorator_from_middleware_with_args(MessageAwareCacheMiddleware)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix
    )
Exemplo n.º 30
0
def cache_page(*args, **kwargs):
    return (decorator_from_middleware_with_args(CacheMiddleware)(*args,
                                                                 **kwargs))
Exemplo n.º 31
0
# coding: utf-8
'''
Decorators for using specific routing state for particular requests.
Used in cases when automatic switching based on request method doesn't
work.

Usage:

    from django_replicated.decorators import use_master, use_slave

    @use_master
    def my_view(request, ...):
        # master database used for all db operations during
        # execution of the view (if not explicitly overriden).

    @use_slave
    def my_view(request, ...):
        # same with slave connection
'''
from __future__ import unicode_literals

from django.utils.decorators import decorator_from_middleware_with_args

from .middleware import ReplicationMiddleware


use_state = decorator_from_middleware_with_args(ReplicationMiddleware)
use_master = use_state('master')
use_slave = use_state('slave')
Exemplo n.º 32
0
from functools import wraps
Exemplo n.º 33
0
                        ' которые возникли при заполнении формы:')
            errors = get_form_errors(form, form.errors.items())

            response = {
                'data': {'message': message, 'errors': errors},
                'code': 400,
            }
    else:
        raise PermissionDenied

    time.sleep(1)

    return HttpResponse(json.dumps(response['data']), status=response['code'])


browser_checker = decorator_from_middleware_with_args(BrowserCheckerMiddleware)


@browser_checker(target_view=True)
def old_browser(request):
    return render(request, 'website/errors/old_browser.html')


@decorator_from_middleware(BrowserCheckerMiddleware)
def handler400(request):
    return render(request, 'website/errors/400.html', {}, status=400)


@decorator_from_middleware(BrowserCheckerMiddleware)
def handler403(request):
    return render(request, 'website/errors/403.html', {}, status=403)
Exemplo n.º 34
0
try:
    from django.utils.decorators import decorator_from_middleware_with_args
except ImportError:
    from lockdown.decutils import decorator_from_middleware_with_args

from lockdown.middleware import LockdownMiddleware

lockdown = decorator_from_middleware_with_args(LockdownMiddleware)
Exemplo n.º 35
0
    # default templates.

    @es_required_or_50x()
    def home_view(request):
        ...


    # This creates a search_view and overrides the templates

    @es_required_or_50x(disabled_template='search/es_disabled.html',
                        error_template('search/es_down.html')
    def search_view(request):
        ...

"""
es_required_or_50x = decorator_from_middleware_with_args(
    ESExceptionMiddleware)


class S(BaseS):
    """S that's based on Django settings"""
    def __init__(self, mapping_type):
        """Create and return an S.

        :arg mapping_type: class; the mapping type that this S is
            based on

        .. Note::

           The :py:class:`elasticutils.S` doesn't require the
           `mapping_type` argument, but the
           :py:class:`elasticutils.contrib.django.S` does.
Exemplo n.º 36
0
from django.http import HttpResponse
from django.views.generic import ListView

import vocabulary.models, vocabulary.customserializers
import vocabulary.customserializers
from django.views import View
from django.apps import apps
from django.utils.module_loading import import_string
from django.utils.decorators import decorator_from_middleware, decorator_from_middleware_with_args

from django.utils.decorators import method_decorator
from middleware import APISecretMiddleware

argsmiddleware = decorator_from_middleware_with_args(APISecretMiddleware)


class APIViewMixin(View):
    apiMiddleware = decorator_from_middleware(APISecretMiddleware)

    @method_decorator(APISecretMiddleware)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)


class CategoriesView(APIViewMixin, View):
    def get(self, request, *args, **kwargs):
        serializer = vocabulary.customserializers.CategorySerialiser()
        b

        return HttpResponse(serializer.serialize(
            vocabulary.models.Categories.objects.all()),
Exemplo n.º 37
0
def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    sites.get_current().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We need backwards compatibility with code which spells it this way:
    #   def my_view(): pass
    #   my_view = cache_page(my_view, 123)
    # and this way:
    #   my_view = cache_page(123)(my_view)
    # and this:
    #   my_view = cache_page(my_view, 123, key_prefix="foo")
    # and this:
    #   my_view = cache_page(123, key_prefix="foo")(my_view)
    # and possibly this way (?):
    #   my_view = cache_page(123, my_view)
    # and also this way:
    #   my_view = cache_page(my_view)
    # and also this way:
    #   my_view = cache_page()(my_view)

    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    # patch start
    tags = kwargs.pop('tags', ())
    assert not kwargs, "The only keyword arguments are cache and key_prefix"

    def warn():
        import warnings
        warnings.warn(
            'The cache_page decorator must be called like: '
            'cache_page(timeout, [cache=cache name], [key_prefix=key prefix]). '
            'All other ways are deprecated.', PendingDeprecationWarning)

    if len(args) > 1:
        assert len(args) == 2, "cache_page accepts at most 2 arguments"
        warn()
        if isinstance(args[0], collections.Callable):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[1],
                cache_alias=cache_alias,
                key_prefix=key_prefix,
                tags=tags)(args[0])
        elif isinstance(args[1], collections.Callable):
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[0],
                cache_alias=cache_alias,
                key_prefix=key_prefix,
                tags=tags)(args[1])
        else:
            assert False, "cache_page must be passed a view function if called with two arguments"
    elif len(args) == 1:
        if isinstance(args[0], collections.Callable):
            warn()
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_alias=cache_alias, key_prefix=key_prefix,
                tags=tags)(args[0])
        else:
            # The One True Way
            return decorator_from_middleware_with_args(CacheMiddleware)(
                cache_timeout=args[0],
                cache_alias=cache_alias,
                key_prefix=key_prefix,
                tags=tags)
    else:
        warn()
        # patch end
        return decorator_from_middleware_with_args(CacheMiddleware)(
            cache_alias=cache_alias, key_prefix=key_prefix, tags=tags)
Exemplo n.º 38
0
from datetime import date

from django.conf import settings
from django.utils.decorators import decorator_from_middleware_with_args
from django.views.decorators.cache import cache_page
from django.middleware.cache import CacheMiddleware


lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
                      cache='eregs_longterm_cache')


class DailyCacheMiddleware(CacheMiddleware):
    """Like the cache middleware, but always expires at midnight"""
    @property
    def key_prefix(self):
        return date.today().isoformat() + '/' + (self.__key_prefix or '')

    @key_prefix.setter
    def key_prefix(self, value):
        self.__key_prefix = value


daily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)(
    cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
    cache_alias='eregs_longterm_cache')
Exemplo n.º 39
0
        self.version_fn = version_fn

    def process_response(self, request, response):
        """Sets the cache, if needed."""
        if request.method != 'GET' or response.status_code != 200:
            return response
        # Logged in users don't cause caching
        if request.user.is_authenticated():
            return response
        try:
            version = response.version
        except AttributeError:
            version = getattr(request.site.state, self.attr)
        key = get_cache_key(
            request.get_host(),
            request.get_full_path(),
            version,
        )
        log.info("CACHE RESPONSE - %s" % key)
        cache.set(
            key,
            response.content,
            self.seconds,
        )
        # Store the version
        response.set_cookie(COOKIE, version)
        return response

cache_page = decorator_from_middleware_with_args(UpdateCacheMiddleware)

Exemplo n.º 40
0
    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
<<<<<<< HEAD
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError("cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
=======
    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=timeout, cache_alias=cache, key_prefix=key_prefix
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
    )


def cache_control(**kwargs):
    def _cache_controller(viewfunc):
<<<<<<< HEAD
        @wraps(viewfunc, assigned=available_attrs(viewfunc))
=======
        @wraps(viewfunc)
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        def _cache_controlled(request, *args, **kw):
Exemplo n.º 41
0
from comrade.core.middleware import PermissionRedirectMiddleware

from functools import wraps


def singleton(cls):
    instances = {}

    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]

    return getinstance


def load_instance(model):
    def decorator(view):
        def _wrapped(request, object_id=None, *args, **kwargs):
            if object_id:
                instance = get_object_or_404(model, pk=object_id)
                return view(request, instance, *args, **kwargs)
            return view(request, *args, **kwargs)

        return wraps(view, assigned=available_attrs(view))(_wrapped)

    return decorator


authorized = decorator_from_middleware_with_args(PermissionRedirectMiddleware)
Exemplo n.º 42
0
class TestMiddleware(SimpleTestCase):
    decorator_factory = decorator_from_middleware_with_args(
        AdvancedCSPMiddleware)

    def setUp(self):
        self.factory = RequestFactory()

    def make_ok_view(self):
        @self.decorator_factory()
        def view(request):
            return HttpResponse('ok')

        return view

    def get_request(self):
        return self.factory.get('/')

    def test_no_csp(self):
        self.assertRaises(MiddlewareNotUsed, self.decorator_factory)

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_new_style(self):
        middleware = AdvancedCSPMiddleware(lambda request: HttpResponse('ok'))
        self.assertEqual(
            middleware(self.get_request())['Content-Security-Policy'],
            "script-src 'self'")

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_setting_csp(self):
        self.assertEqual(
            self.make_ok_view()(self.get_request())['Content-Security-Policy'],
            "script-src 'self'")

    @override_settings(ADVANCED_CSP='verbatim bad csp')
    def test_setting_str(self):
        self.assertEqual(
            self.make_ok_view()(self.get_request())['Content-Security-Policy'],
            'verbatim bad csp')

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_csp_exists(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response['Content-Security-Policy'] = 'verbatim bad csp'
            return response

        self.assertEqual(
            view(self.get_request())['Content-Security-Policy'],
            'verbatim bad csp')

    @override_settings(ADVANCED_CSP={'bad': ['self']})
    def test_invalid_csp(self):
        self.assertFalse('Content-Security-Policy' in self.make_ok_view()(
            self.get_request()))

    @override_settings(
        ADVANCED_CSP_REPORT_ONLY={'default-src': ['http://dmoj.ca']})
    def test_setting_csp_report(self):
        self.assertEqual(
            self.make_ok_view()(
                self.get_request())['Content-Security-Policy-Report-Only'],
            "default-src http://dmoj.ca")

    @override_settings(
        ADVANCED_CSP={'script-src': ['self']},
        ADVANCED_CSP_REPORT_ONLY={'default-src': ['http://dmoj.ca']})
    def test_setting_both(self):
        response = self.make_ok_view()(self.get_request())
        self.assertEqual(response['Content-Security-Policy'],
                         "script-src 'self'")
        self.assertEqual(response['Content-Security-Policy-Report-Only'],
                         'default-src http://dmoj.ca')

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_merge_csp_same(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'script-src': ['https://dmoj.ca']}
            return response

        self.assertEqual(
            view(self.get_request())['Content-Security-Policy'],
            "script-src 'self' https://dmoj.ca")

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_merge_csp_different(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'style-src': ['https://dmoj.ca']}
            return response

        self.assertEqual(
            sorted(
                view(self.get_request())['Content-Security-Policy'].split(
                    '; ')), ["script-src 'self'", 'style-src https://dmoj.ca'])

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_override_csp_explicit(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'style-src': ['none'], 'override': True}
            return response

        self.assertEqual(
            view(self.get_request())['Content-Security-Policy'],
            "style-src 'none'")

    @override_settings(ADVANCED_CSP={'script-src': ['self']})
    def test_remove_csp(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'override': True}
            return response

        self.assertFalse('Content-Security-Policy' in view(self.get_request()))

    @override_settings(ADVANCED_CSP_REPORT_ONLY={'script-src': ['self']})
    def test_override_csp_to_report_explicit(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'style-src': ['none'], 'override': True}
            return response

        self.assertEqual(
            view(self.get_request())['Content-Security-Policy-Report-Only'],
            "style-src 'none'")

    @override_settings(ADVANCED_CSP_REPORT_ONLY={'script-src': ['self']})
    def test_override_csp_report_both_explicit(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp = {'style-src': ['none'], 'override': True}
            response.csp_report = {'script-src': ['none'], 'override': True}
            return response

        response = view(self.get_request())
        self.assertEqual(response['Content-Security-Policy-Report-Only'],
                         "script-src 'none'")
        self.assertFalse('Content-Security-Policy' in response)

    @override_settings(ADVANCED_CSP_REPORT_ONLY={'script-src': ['self']})
    def test_override_csp_report_only_explicit(self):
        @self.decorator_factory()
        def view(request):
            response = HttpResponse()
            response.csp_report = {'script-src': ['none'], 'override': True}
            return response

        response = view(self.get_request())
        self.assertEqual(response['Content-Security-Policy-Report-Only'],
                         "script-src 'none'")
        self.assertFalse('Content-Security-Policy' in response)
Exemplo n.º 43
0
# Copyright (c) 2008 Participatory Culture Foundation
# See LICENSE for details.

from middleware import UserCacheMiddleware
from middleware import SiteHidingCacheMiddleware, APICacheMiddleware
from django.utils.decorators import (decorator_from_middleware,
                                     decorator_from_middleware_with_args)

cache_with_sites = decorator_from_middleware_with_args(
    SiteHidingCacheMiddleware)
cache_for_user = decorator_from_middleware(UserCacheMiddleware)
api_cache = decorator_from_middleware(APICacheMiddleware)
Exemplo n.º 44
0
def cache_page(*args, **kwargs):
    cache_alias = kwargs.pop('cache', None)
    return (decorator_from_middleware_with_args(CacheMiddleware)(
        cache_alias=cache_alias, *args, **kwargs))
Exemplo n.º 45
0
def cache_page(*args, **kwargs):
    cache_alias = kwargs.pop('cache', None)
    return (
        decorator_from_middleware_with_args
        (CacheMiddleware)(cache_alias=cache_alias, *args, **kwargs)
    )
Exemplo n.º 46
0
        backend = backend if backend is not None else settings.BACKEND
        if isinstance(backend, str):
            backend = import_string(backend)
        self.backend = backend()

    def __call__(self, request: HttpRequest) -> HttpResponse:
        if self.must_render(request):
            return self.backend.render(self.backend.build_absolute_url(request))
        return self.get_response(request)

    def must_render(self, request: HttpRequest) -> bool:
        """
        Return `True` if request must be rendered by backend.
        """
        raise NotImplementedError('%s.must_render is not implemented' % self.__class__.__name__)


class UserAgentMiddleware(BaseMiddleware):
    """
    Render page if request's User-Agent matches `settings.DJANGO_SSR_USER_AGENTS`
    """

    def must_render(self, request: HttpRequest) -> bool:
        ua = request.META.get('HTTP_USER_AGENT', '')
        url = self.backend.build_absolute_url(request)
        return helpers.is_user_agent_match(ua) and helpers.must_render(url)


user_agent_ssr = decorator_from_middleware_with_args(UserAgentMiddleware)
Exemplo n.º 47
0
 def cache_page_with_prefix(*args, **kwargs):
     return decorator_from_middleware_with_args(CacheMiddleware)(*args)