예제 #1
0
def settings(request=None):
    """
    Add the settings object to the template context.
    """
    from mezzanine.conf import settings
    settings_dict = None
    cache_settings = request and cache_installed()
    if cache_settings:
        cache_key = cache_key_prefix(request) + "context-settings"
        settings_dict = cache_get(cache_key)
    if not settings_dict:
        settings.use_editable()
        settings_dict = TemplateSettings()
        for k in settings.TEMPLATE_ACCESSIBLE_SETTINGS:
            settings_dict[k] = getattr(settings, k, "")
        for k in DEPRECATED:
            settings_dict[k] = getattr(settings, k, DEPRECATED)
        if cache_settings:
            cache_set(cache_key, settings_dict)
    # This is basically the same as the old ADMIN_MEDIA_PREFIX setting,
    # we just use it in a few spots in the admin to optionally load a
    # file from either grappelli or Django admin if grappelli isn't
    # installed. We don't call it ADMIN_MEDIA_PREFIX in order to avoid
    # any confusion.
    if settings.GRAPPELLI_INSTALLED:
        settings_dict["MEZZANINE_ADMIN_PREFIX"] = "grappelli/"
    else:
        settings_dict["MEZZANINE_ADMIN_PREFIX"] = "admin/"
    return {"settings": settings_dict}
예제 #2
0
def settings(request=None):
    """
    Add the settings object to the template context.
    """
    from mezzanine.conf import settings
    settings_dict = None
    cache_settings = request and cache_installed()
    if cache_settings:
        cache_key = (cache_key_prefix(request, ignore_device=True) +
                     "context-settings")
        settings_dict = cache_get(cache_key)
    if not settings_dict:
        settings.use_editable()
        settings_dict = TemplateSettings()
        for k in settings.TEMPLATE_ACCESSIBLE_SETTINGS:
            settings_dict[k] = getattr(settings, k, "")
        for k in DEPRECATED:
            settings_dict[k] = getattr(settings, k, DEPRECATED)
        if cache_settings:
            cache_set(cache_key, settings_dict)
    # This is basically the same as the old ADMIN_MEDIA_PREFIX setting,
    # we just use it in a few spots in the admin to optionally load a
    # file from either grappelli or Django admin if grappelli isn't
    # installed. We don't call it ADMIN_MEDIA_PREFIX in order to avoid
    # any confusion.
    if settings.GRAPPELLI_INSTALLED:
        settings_dict["MEZZANINE_ADMIN_PREFIX"] = "grappelli/"
    else:
        settings_dict["MEZZANINE_ADMIN_PREFIX"] = "admin/"
    return {"settings": settings_dict}
예제 #3
0
 def process_request(self, request):
     if cache_installed() and request.method == "GET" and not request.user.is_authenticated():
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #4
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
         not request.user.is_authenticated()):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #5
0
    def process_response(self, request, response):

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, incicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not request.user.is_authenticated()
        valid_status = response.status_code == 200
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        content_type = response.get("content-type", "")
        if content_type.startswith("text") and len(parts) > 1:
            # Restore csrf token from cookie - check the response
            # first as it may be being set for the first time.
            csrf_token = None
            try:
                csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
            except KeyError:
                try:
                    csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
                except KeyError:
                    pass
            if csrf_token:
                request.META["CSRF_COOKIE"] = csrf_token
            context = RequestContext(request)
            for i, part in enumerate(parts):
                if i % 2:
                    part = Template(part).render(context).encode("utf-8")
                parts[i] = part
            response.content = b"".join(parts)
            response["Content-Length"] = len(response.content)
            if hasattr(request, '_messages'):
                # Required to clear out user messages.
                request._messages.update(response)
        return response
예제 #6
0
    def process_response(self, request, response):

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, incicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not request.user.is_authenticated()
        valid_status = response.status_code == 200
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        content_type = response.get("content-type", "")
        if content_type.startswith("text") and len(parts) > 1:
            # Restore csrf token from cookie - check the response
            # first as it may be being set for the first time.
            csrf_token = None
            try:
                csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
            except KeyError:
                try:
                    csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
                except KeyError:
                    pass
            if csrf_token:
                request.META["CSRF_COOKIE"] = csrf_token
            context = RequestContext(request)
            for i, part in enumerate(parts):
                if i % 2:
                    part = Template(part).render(context).encode("utf-8")
                parts[i] = part
            response.content = b"".join(parts)
            response["Content-Length"] = len(response.content)
            if hasattr(request, '_messages'):
                # Required to clear out user messages.
                request._messages.update(response)
        return response
예제 #7
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
         not request.user.is_authenticated()):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         if response is None:
             request._update_cache = True
         else:
             csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
             if csrf_mw_name in settings.MIDDLEWARE_CLASSES:
                 csrf_mw = CsrfViewMiddleware()
                 csrf_mw.process_view(request, lambda x: None, None, None)
                 get_token(request)
             return HttpResponse(response)
예제 #8
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET"
             and not request.user.is_authenticated()):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         if response is None:
             request._update_cache = True
         else:
             csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
             if csrf_mw_name in settings.MIDDLEWARE_CLASSES:
                 csrf_mw = CsrfViewMiddleware()
                 csrf_mw.process_view(request, lambda x: None, None, None)
                 get_token(request)
             return HttpResponse(response)
예제 #9
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET"
             and not is_authenticated(request.user)):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receieve one on their first request, with cache
         # middleware running.
         if csrf_middleware_installed():
             csrf_mw = CsrfViewMiddleware()
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #10
0
 def process_request(self, request):
     if (cache_installed() and request.method == "GET" and
             not is_authenticated(request.user)):
         cache_key = cache_key_prefix(request) + request.get_full_path()
         response = cache_get(cache_key)
         # We need to force a csrf token here, as new sessions
         # won't receieve one on their first request, with cache
         # middleware running.
         if csrf_middleware_installed():
             csrf_mw = CsrfViewMiddleware()
             csrf_mw.process_view(request, lambda x: None, None, None)
             get_token(request)
         if response is None:
             request._update_cache = True
         else:
             return HttpResponse(response)
예제 #11
0
def settings(request):
    """
    Add the settings object to the template context.
    """
    settings_dict = None
    if cache_installed():
        cache_key = cache_key_prefix(request) + "context-settings"
        settings_dict = cache_get(cache_key)
    if not settings_dict:
        from mezzanine.conf import settings
        settings.use_editable()
        settings_dict = dict([(k, getattr(settings, k, ""))
                              for k in settings.TEMPLATE_ACCESSIBLE_SETTINGS])
        if cache_installed():
            cache_set(cache_key, settings_dict)
    return {"settings": type("Settings", (), settings_dict)}
예제 #12
0
파일: admin.py 프로젝트: Kniyl/mezzanine
 def changelist_view(self, request, extra_context=None):
     if extra_context is None:
         extra_context = {}
     settings_form = SettingsForm(request.POST or None)
     if settings_form.is_valid():
         settings_form.save()
         info(request, _("Settings were successfully updated."))
         if cache_installed():
             cache_key = (cache_key_prefix(request, ignore_device=True) +
                          "context-settings")
             cache_delete(cache_key)
         return self.changelist_redirect()
     extra_context["settings_form"] = settings_form
     extra_context["title"] = u"%s %s" % (
         _("Change"), force_text(Setting._meta.verbose_name_plural))
     return super(SettingsAdmin, self).changelist_view(request,
                                                         extra_context)
예제 #13
0
 def changelist_view(self, request, extra_context=None):
     if extra_context is None:
         extra_context = {}
     settings_form = SettingsForm(request.POST or None)
     if settings_form.is_valid():
         settings_form.save()
         info(request, _("Settings were successfully updated."))
         if cache_installed():
             cache_key = (cache_key_prefix(request, ignore_device=True) +
                          "context-settings")
             cache_delete(cache_key)
         return self.changelist_redirect()
     extra_context["settings_form"] = settings_form
     extra_context["title"] = u"%s %s" % (
         _("Change"), force_text(Setting._meta.verbose_name_plural))
     return super(SettingsAdmin,
                  self).changelist_view(request, extra_context)
예제 #14
0
def settings(request):
    """
    Add the settings object to the template context.
    """
    settings_dict = None
    if cache_installed():
        cache_key = cache_key_prefix(request) + "context-settings"
        settings_dict = cache_get(cache_key)
    if not settings_dict:
        from mezzanine.conf import settings
        settings.use_editable()
        settings_dict = TemplateSettings()
        for k in settings.TEMPLATE_ACCESSIBLE_SETTINGS:
            settings_dict[k] = getattr(settings, k, "")
        for k in DEPRECATED:
            settings_dict[k] = getattr(settings, k, DEPRECATED)
        if cache_installed():
            cache_set(cache_key, settings_dict)
    return {"settings": settings_dict}
예제 #15
0
    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not is_authenticated(request.user)
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, '_messages'):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
        if csrf_mw_name in get_middleware_setting():
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response
예제 #16
0
    def process_response(self, request, response):

        # Caching is only applicable for text-based, non-streaming
        # responses. We also skip it for non-200 statuses during
        # development, so that stack traces are correctly rendered.
        is_text = response.get("content-type", "").startswith("text")
        valid_status = response.status_code == 200
        streaming = getattr(response, "streaming", False)
        if not is_text or streaming or (settings.DEBUG and not valid_status):
            return response

        # Cache the response if all the required conditions are met.
        # Response must be marked for updating by the
        # ``FetchFromCacheMiddleware`` having a cache get miss, the
        # user must not be authenticated, the HTTP status must be OK
        # and the response mustn't include an expiry age, indicating it
        # shouldn't be cached.
        marked_for_update = getattr(request, "_update_cache", False)
        anon = hasattr(request, "user") and not request.user.is_authenticated()
        timeout = get_max_age(response)
        if timeout is None:
            timeout = settings.CACHE_MIDDLEWARE_SECONDS
        if anon and valid_status and marked_for_update and timeout:
            cache_key = cache_key_prefix(request) + request.get_full_path()
            _cache_set = lambda r: cache_set(cache_key, r.content, timeout)
            if callable(getattr(response, "render", None)):
                response.add_post_render_callback(_cache_set)
            else:
                _cache_set(response)

        # Second phase rendering for non-cached template code and
        # content. Split on the delimiter the ``nevercache`` tag
        # wrapped its contents in, and render only the content
        # enclosed by it, to avoid possible template code injection.
        token = nevercache_token()
        try:
            token = token.encode('utf-8')
        except AttributeError:
            pass
        parts = response.content.split(token)
        # Restore csrf token from cookie - check the response
        # first as it may be being set for the first time.
        csrf_token = None
        try:
            csrf_token = response.cookies[settings.CSRF_COOKIE_NAME].value
        except KeyError:
            try:
                csrf_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
            except KeyError:
                pass
        if csrf_token:
            request.META["CSRF_COOKIE"] = csrf_token
        context = RequestContext(request)
        for i, part in enumerate(parts):
            if i % 2:
                part = Template(part).render(context).encode("utf-8")
            parts[i] = part
        response.content = b"".join(parts)
        response["Content-Length"] = len(response.content)
        if hasattr(request, '_messages'):
            # Required to clear out user messages.
            request._messages.update(response)
        # Response needs to be run-through the CSRF middleware again so
        # that if there was a {% csrf_token %} inside of the nevercache
        # the cookie will be correctly set for the the response
        csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware"
        if csrf_mw_name in MIDDLEWARE_SETTING:
            response.csrf_processing_done = False
            csrf_mw = CsrfViewMiddleware()
            csrf_mw.process_response(request, response)
        return response