Beispiel #1
0
    def search_view(self, request, **kwargs):
        fields = self.list_fields or ['pk']
        q = request.GET.get('q', None)
        qs = []

        # Makes the cache key
        cache_key = self.make_search_cache_key(q)

        # Tries to return from cache first
        from_cache = cache.get(cache_key)
        if from_cache:
            return JsonResponse(from_cache)

        if q and self.search_fields:
            # Basic query
            qs = self.get_queryset(request)

            # Filter by query string
            criteria = dict([(k+'__icontains',q) for k in self.search_fields])
            qs = qs.filter_if_any(**criteria)

            # Converts to values
            qs = qs.values(*fields)

            # Limited list results
            max_results = min([int(request.GET.get('_max', self.max_results)), self.max_results])
            if max_results:
                qs = qs[:max_results]

        # Prepares for JSON and to store in cache
        results = [self.prepare_for_json(obj) for obj in qs]
        if app_settings.CACHE_TIMEOUT:
            cache.set(cache_key, results, app_settings.CACHE_TIMEOUT)

        return JsonResponse(results)
Beispiel #2
0
def minify(content, ext):
    """Uses YUICompressor to minify JavaScript and CSS content."""
    hsh = hashlib.sha1(content).hexdigest()
    cache_key = 'minify-'+hsh

    # Loads from cache
    ret = cache.get(cache_key, None)
    if ret: return ret

    jar_path = app_settings.YUICOMPRESSOR_PATH
    
    # Saves content in temporary file
    f_name = hsh
    f_path = os.path.join(settings.TEMP_DIR, '%s-all.%s'%(f_name, ext))
    new_path = os.path.join(settings.TEMP_DIR, '%s-min.%s'%(f_name, ext))
    fp = file(f_path, 'w')
    fp.write(content)
    fp.close()

    # Runs YUICompressor
    os.system("%s -o %s %s"%(jar_path, new_path, f_path))

    if app_settings.MINIFY and os.path.exists(new_path):
        # Checks if the minified file exists, otherwise returns the merged one
        fp = file(new_path)
        content = fp.read()
        fp.close()

    # Saves in cache
    cache.set(cache_key, content)

    return content
Beispiel #3
0
    def get_source(self, environment, template):
        if ":" in template:
            active_theme, template_name = template.split(":", 1)
            active_theme = Theme.query().get(name=active_theme)
        elif getattr(environment, "theme", None):
            template_name = template
            active_theme = environment.theme
        else:
            template_name = template
            active_theme = None
            if app_settings.CACHE_EXPIRATION:
                try:
                    active_theme = Theme.query().get(pk=cache.get("themes:active", None))
                except Theme.DoesNotExist:
                    pass

            if not active_theme:
                try:
                    theme = Theme.query().get(is_default=True)
                    if app_settings.CACHE_EXPIRATION:
                        cache.set("themes:active", theme["pk"], app_settings.CACHE_EXPIRATION)
                    active_theme = theme
                except Theme.DoesNotExist:
                    # raise JinjaTemplateNotFound('There\'s no active theme.')
                    pass

        try:
            reg_template = get_registered_template(template)
        except KeyError:
            if app_settings.ALLOW_NOT_REGISTERED:
                reg_template = {}
            else:
                raise JinjaTemplateNotFound('Template "%s" is not registered.' % template)

        content = None
        uptodate = lambda: True
        full_name = None
        engine = None
        if active_theme:
            try:
                # Using cache to restore/store template content
                cache_key = "themes:%s|%s" % (active_theme["name"], template_name)
                content = cache.get(cache_key, None) if app_settings.CACHE_EXPIRATION else None

                if not content or not content.split(";", 1)[-1] or content.split(";", 1)[-1] == "None":
                    tpl = ThemeTemplate.query().get(theme=active_theme, name=template_name)
                    engine = tpl["engine"]
                    content = tpl["content"]
                    if app_settings.CACHE_EXPIRATION:
                        cache.set(cache_key, "engine:%s;%s" % (engine, content or ""), app_settings.CACHE_EXPIRATION)

                full_name = "%s:%s" % (active_theme["name"], template_name)
            except ThemeTemplate.DoesNotExist:
                content = None

        if reg_template and not content:
            content = reg_template.get("content", None)

        if not content:
            if (
                reg_template
                and reg_template.get("mirroring", None)
                and reg_template.get("mirroring", None) != template_name
            ):
                # Trying this firstly...
                try:
                    return self.get_source(environment, reg_template["mirroring"])
                except JinjaTemplateNotFound as e:
                    pass

                # If get no success, tries by the hardest way, from file system...
                ret = environment.get_template(reg_template["mirroring"])
                if ret:
                    f = open(ret.filename)
                    try:
                        contents = f.read()
                    finally:
                        f.close()
                    return contents.decode("utf-8"), ret.filename, ret.is_up_to_date
            raise JinjaTemplateNotFound('Template "%s" doesn\'t exist in active theme.' % template_name)

        if content.startswith("engine:"):
            engine, content = content.split(";", 1)
            engine = engine.split(":")[1]

        return content, full_name, uptodate
Beispiel #4
0
def themetemplate_post_save(instance, sender, **kwargs):
    # Cache invalidation
    cache_key = 'themes:%s|%s'%(instance['theme']['name'], instance['name'])
    if app_settings.CACHE_EXPIRATION and cache.get(cache_key):
        cache.set(cache_key, None, 1) # Expires fastly, to clear cache storage