Esempio n. 1
0
def settings(request):
    """
    Add the settings object to the template context.
    """
    from mezzanine.conf import settings
    settings_dict = None
    if cache_installed():
        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_installed():
            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}
def settings(request):
    """
    Add the settings object to the template context.
    """
    from mezzanine.conf import settings
    settings_dict = None
    if cache_installed():
        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_installed():
            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}
Esempio n. 3
0
def current_site_id():
    """
    Responsible for determining the current ``Site`` instance to use
    when retrieving data for any ``SiteRelated`` models. If we're inside an
    override_current_site_id context manager, return the overriding site ID.
    Otherwise, try to determine the site using the following methods in order:

      - ``site_id`` in session. Used in the admin so that admin users
        can switch sites and stay on the same domain for the admin.
      - The id of the Site object corresponding to the hostname in the current
        request. This result is cached.
      - ``MEZZANINE_SITE_ID`` environment variable, so management
        commands or anything else outside of a request can specify a
        site.
      - ``SITE_ID`` setting.

    If a current request exists and the current site is not overridden, the
    site ID is stored on the request object to speed up subsequent calls.
    """

    if hasattr(override_current_site_id.thread_local, "site_id"):
        return override_current_site_id.thread_local.site_id

    from mezzanine.utils.cache import cache_installed, cache_get, cache_set
    request = current_request()
    site_id = getattr(request, "site_id", None)
    if request and not site_id:
        site_id = request.session.get("site_id", None)
        if not site_id:
            domain = request.get_host().lower()
            if cache_installed():
                # Don't use Mezzanine's cache_key_prefix here, since it
                # uses this very function we're in right now to create a
                # per-site cache key.
                bits = (settings.CACHE_MIDDLEWARE_KEY_PREFIX, domain)
                cache_key = "%s.site_id.%s" % bits
                site_id = cache_get(cache_key)
            if not site_id:
                try:
                    site = Site.objects.get(domain__iexact=domain)
                except Site.DoesNotExist:
                    pass
                else:
                    site_id = site.id
                    if cache_installed():
                        cache_set(cache_key, site_id)
    if not site_id:
        try:
            cur_language = translation.get_language()
            site_id = settings.LANGUAGE_SITE_MAP[cur_language]
        except KeyError:
            site_id = os.environ.get("MEZZANINE_SITE_ID", settings.SITE_ID)
            msg = 'Please add language %s to settings.LANGUAGE_SITE_MAP'
            sys.stdout.write(msg % cur_language)
    if request and site_id and not getattr(settings, "TESTING", False):
        request.site_id = site_id
    return site_id
Esempio n. 4
0
def current_site_id():
    """
    Responsible for determining the current ``Site`` instance to use
    when retrieving data for any ``SiteRelated`` models. If we're inside an
    override_current_site_id context manager, return the overriding site ID.
    Otherwise, try to determine the site using the following methods in order:

      - ``site_id`` in session. Used in the admin so that admin users
        can switch sites and stay on the same domain for the admin.
      - The id of the Site object corresponding to the hostname in the current
        request. This result is cached.
      - ``MEZZANINE_SITE_ID`` environment variable, so management
        commands or anything else outside of a request can specify a
        site.
      - ``SITE_ID`` setting.

    If a current request exists and the current site is not overridden, the
    site ID is stored on the request object to speed up subsequent calls.
    """

    if hasattr(override_current_site_id.thread_local, "site_id"):
        return override_current_site_id.thread_local.site_id

    from mezzanine.utils.cache import cache_installed, cache_get, cache_set
    request = current_request()
    site_id = getattr(request, "site_id", None)
    if request and not site_id:
        site_id = request.session.get("site_id", None)
        if not site_id:
            domain = request.get_host().lower()
            if cache_installed():
                # Don't use Mezzanine's cache_key_prefix here, since it
                # uses this very function we're in right now to create a
                # per-site cache key.
                bits = (settings.CACHE_MIDDLEWARE_KEY_PREFIX, domain)
                cache_key = "%s.site_id.%s" % bits
                site_id = cache_get(cache_key)
            if not site_id:
                try:
                    site = Site.objects.get(domain__iexact=domain)
                except Site.DoesNotExist:
                    pass
                else:
                    site_id = site.id
                    if cache_installed():
                        cache_set(cache_key, site_id)
    if not site_id:
        try:
            cur_language = translation.get_language()
            site_id = settings.LANGUAGE_SITE_MAP[cur_language]
        except KeyError:
            site_id = os.environ.get("MEZZANINE_SITE_ID", settings.SITE_ID)
            msg = 'Please add language %s to settings.LANGUAGE_SITE_MAP'
            sys.stdout.write(msg % cur_language)
    if request and site_id and not getattr(settings, "TESTING", False):
        request.site_id = site_id
    return site_id
Esempio n. 5
0
def current_site_id():
    """
    Responsible for determining the current ``Site`` instance to use
    when retrieving data for any ``SiteRelated`` models. If a request
    is available, and the site can be determined from it, we store the
    site against the request for subsequent retrievals. Otherwise the
    order of checks is as follows:

      - ``site_id`` in session. Used in the admin so that admin users
        can switch sites and stay on the same domain for the admin.
      - host for the current request matched to the domain of the site
        instance.
      - ``MEZZANINE_SITE_ID`` environment variable, so management
        commands or anything else outside of a request can specify a
        site.
      - ``SITE_ID`` setting.

    """
    from mezzanine.utils.cache import cache_installed, cache_get, cache_set
    request = current_request()
    site_id = getattr(request, "site_id", None)
    if request and not site_id:
        site_id = request.session.get("site_id", None)
        if not site_id:
            domain = request.get_host().lower()
            if cache_installed():
                # Don't use Mezzanine's cache_key_prefix here, since it
                # uses this very function we're in right now to create a
                # per-site cache key.
                bits = (settings.CACHE_MIDDLEWARE_KEY_PREFIX, domain)
                cache_key = "%s.site_id.%s" % bits
                site_id = cache_get(cache_key)
            if not site_id:
                try:
                    site = Site.objects.get(domain__iexact=domain)
                except Site.DoesNotExist:
                    pass
                else:
                    site_id = site.id
                    if cache_installed():
                        cache_set(cache_key, site_id)
            if request and site_id:
                request.site_id = site_id
    if not site_id:
        site_id = os.environ.get("MEZZANINE_SITE_ID", settings.SITE_ID)
    if request and site_id and not getattr(settings, "TESTING", False):
        request.site_id = site_id
    return site_id
Esempio n. 6
0
def current_site_id():
    """
    Responsible for determining the current ``Site`` instance to use
    when retrieving data for any ``SiteRelated`` models. If a request
    is available, and the site can be determined from it, we store the
    site against the request for subsequent retrievals. Otherwise the
    order of checks is as follows:

      - ``site_id`` in session. Used in the admin so that admin users
        can switch sites and stay on the same domain for the admin.
      - host for the current request matched to the domain of the site
        instance.
      - ``MEZZANINE_SITE_ID`` environment variable, so management
        commands or anything else outside of a request can specify a
        site.
      - ``SITE_ID`` setting.

    """
    from mezzanine.utils.cache import cache_installed, cache_get, cache_set
    request = current_request()
    site_id = getattr(request, "site_id", None)
    if request and not site_id:
        site_id = request.session.get("site_id", None)
        if not site_id:
            domain = request.get_host().lower()
            if cache_installed():
                # Don't use Mezzanine's cache_key_prefix here, since it
                # uses this very function we're in right now to create a
                # per-site cache key.
                bits = (settings.CACHE_MIDDLEWARE_KEY_PREFIX, domain)
                cache_key = "%s.site_id.%s" % bits
                site_id = cache_get(cache_key)
            if not site_id:
                try:
                    site = Site.objects.get(domain__iexact=domain)
                except Site.DoesNotExist:
                    pass
                else:
                    site_id = site.id
                    if cache_installed():
                        cache_set(cache_key, site_id)
            if request and site_id:
                request.site_id = site_id
    if not site_id:
        site_id = os.environ.get("MEZZANINE_SITE_ID", settings.SITE_ID)
    if request and site_id and not getattr(settings, "TESTING", False):
        request.site_id = site_id
    return site_id
Esempio n. 7
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)}
Esempio n. 8
0
def initialize_nevercache():
    if cache_installed():
        @register.tag
        def nevercache(parser, token):
            """
            Tag for two phased rendering. Converts enclosed template
            code and content into text, which gets rendered separately
            in ``mezzanine.core.middleware.UpdateCacheMiddleware``.
            This is to bypass caching for the enclosed code and content.
            """
            text = []
            end_tag = "endnevercache"
            tag_mapping = {
                TOKEN_TEXT: ("", ""),
                TOKEN_VAR: ("{{", "}}"),
                TOKEN_BLOCK: ("{%", "%}"),
                TOKEN_COMMENT: ("{#", "#}"),
            }
            delimiter = nevercache_token()
            while parser.tokens:
                token = parser.next_token()
                token_type = token.token_type
                if token_type == TOKEN_BLOCK and token.contents == end_tag:
                    return TextNode(delimiter + "".join(text) + delimiter)
                start, end = tag_mapping[token_type]
                text.append("%s%s%s" % (start, token.contents, end))
            parser.unclosed_block_tag(end_tag)
    else:
        @register.to_end_tag
        def nevercache(parsed, context, token):
            """
            Dummy fallback ``nevercache`` for when caching is not
            configured.
            """
            return parsed
Esempio n. 9
0
    def test_cache_installed(self):

        test_contexts = [
            (False,
             ['mezzanine.core.middleware.FetchFromCacheMiddleware']),
            (True,
             ['mezzanine.core.middleware.UpdateCacheMiddleware',
              'mezzanine.core.tests.SubclassMiddleware']),
            (True,
             ['mezzanine.core.middleware.UpdateCacheMiddleware',
              'mezzanine.core.tests.FetchFromCacheMiddleware',
              'mezzanine.core.tests.function_middleware']),
            (True,
             ['mezzanine.core.middleware.UpdateCacheMiddleware',
              'mezzanine.core.middleware.FetchFromCacheMiddleware']),
        ]

        with self.settings(TESTING=False):  # Well, this is silly
            for expected_result, middlewares in test_contexts:
                kwargs = {get_middleware_setting_name(): middlewares}
                with self.settings(**kwargs):
                    cache_installed.cache_clear()
                    self.assertEqual(cache_installed(), expected_result)

        cache_installed.cache_clear()
Esempio n. 10
0
def initialize_nevercache():
    if cache_installed():
        @register.tag
        def nevercache(parser, token):
            """
            Tag for two phased rendering. Converts enclosed template
            code and content into text, which gets rendered separately
            in ``mezzanine.core.middleware.UpdateCacheMiddleware``.
            This is to bypass caching for the enclosed code and content.
            """
            text = []
            end_tag = "endnevercache"
            tag_mapping = {
                TOKEN_TEXT: ("", ""),
                TOKEN_VAR: ("{{", "}}"),
                TOKEN_BLOCK: ("{%", "%}"),
                TOKEN_COMMENT: ("{#", "#}"),
            }
            delimiter = nevercache_token()
            while parser.tokens:
                token = parser.next_token()
                token_type = token.token_type
                if token_type == TOKEN_BLOCK and token.contents == end_tag:
                    return TextNode(delimiter + "".join(text) + delimiter)
                start, end = tag_mapping[token_type]
                text.append("%s%s%s" % (start, token.contents, end))
            parser.unclosed_block_tag(end_tag)
    else:
        @register.to_end_tag
        def nevercache(parsed, context, token):
            """
            Dummy fallback ``nevercache`` for when caching is not
            configured.
            """
            return parsed
Esempio n. 11
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)
Esempio n. 12
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)
Esempio n. 13
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}
Esempio n. 14
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)
Esempio n. 15
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)
Esempio n. 16
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)
Esempio n. 17
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)
Esempio n. 18
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)
Esempio n. 19
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)
Esempio n. 20
0
    def test_cache_installed(self):

        test_contexts = [
            (False,
             ['mezzanine.core.middleware.FetchFromCacheMiddleware']),
            (True,
             ['mezzanine.core.middleware.UpdateCacheMiddleware',
              'mezzanine.core.tests.SubclassMiddleware']),
            (True,
             ['mezzanine.core.middleware.UpdateCacheMiddleware',
              'mezzanine.core.middleware.FetchFromCacheMiddleware']),
        ]

        with self.settings(TESTING=False):  # Well, this is silly
            for expected_result, middleware_classes in test_contexts:
                with self.settings(MIDDLEWARE_CLASSES=middleware_classes):
                    cache_installed.cache_clear()
                    self.assertEqual(cache_installed(), expected_result)

        cache_installed.cache_clear()
Esempio n. 21
0
 def get_for(self, user_name=None, list_name=None, search_term=None):
     """
     Create a query and run it for the given arg if it doesn't exist, and
     return the tweets for the query.
     """
     if user_name is not None:
         type, value = "user", user_name
     elif list_name is not None:
         type, value = "list", list_name
     elif search_term is not None:
         type, value = "search", search_term
     else:
         return
     from mezzanine.twitter.models import Query
     query, created = Query.objects.get_or_create(type=type, value=value)
     if created or cache_installed():
         query.run()
     elif not query.interested:
         query.interested = True
         query.save()
     return query.tweets.all()
Esempio n. 22
0
        loaded from ``mezzanine_tags``, allowing us to provide
        a dummy version when django-compressor isn't installed.
        """
        from compressor.templatetags.compress import compress
        return compress(parser, token)
else:

    @register.to_end_tag
    def compress(parsed, context, token):
        """
        Dummy tag for fallback when django-compressor isn't installed.
        """
        return parsed


if cache_installed():

    @register.tag
    def nevercache(parser, token):
        """
        Tag for two phased rendering. Converts enclosed template
        code and content into text, which gets rendered separately
        in ``mezzanine.core.middleware.UpdateCacheMiddleware``.
        This is to bypass caching for the enclosed code and content.
        """
        text = []
        end_tag = "endnevercache"
        tag_mapping = {
            TOKEN_TEXT: ("", ""),
            TOKEN_VAR: ("{{", "}}"),
            TOKEN_BLOCK: ("{%", "%}"),
Esempio n. 23
0
        from compressor.templatetags.compress import compress

        return compress(parser, token)


else:

    @register.to_end_tag
    def compress(parsed, context, token):
        """
        Dummy tag for fallback when django-compressor isn't installed.
        """
        return parsed


if cache_installed():

    @register.tag
    def nevercache(parser, token):
        """
        Tag for two phased rendering. Converts enclosed template
        code and content into text, which gets rendered separately
        in ``mezzanine.core.middleware.UpdateCacheMiddleware``.
        This is to bypass caching for the enclosed code and content.
        """
        text = []
        end_tag = "endnevercache"
        tag_mapping = {
            TOKEN_TEXT: ("", ""),
            TOKEN_VAR: ("{{", "}}"),
            TOKEN_BLOCK: ("{%", "%}"),