Beispiel #1
0
 def get_listing(self, i):
     Listing = get_model('core', 'listing')
     return Listing.objects.get_listing_queryset(
             self.category,
             children=self.children,
             content_types=self.content_types,
             date_range=self.date_range,
             exclude=self.exclude
         )[i]
Beispiel #2
0
 def count(self):
     if not hasattr(self, '_count'):
         Listing = get_model('core', 'listing')
         self._count = Listing.objects.get_listing_queryset(
             self.category,
             children=self.children,
             content_types=self.content_types,
             date_range=self.date_range,
             exclude=self.exclude
         ).count()
     return self._count
Beispiel #3
0
 def get_listings(self, offset=0, count=10):
     Listing = get_model('core', 'listing')
     return Listing.objects.get_listing(
             self.category,
             children=self.children,
             content_types=self.content_types,
             date_range=self.date_range,
             offset=offset,
             count=count,
             exclude=self.exclude
         )
Beispiel #4
0
def parse_related_tag(bits):
    if len(bits) < 6:
        raise template.TemplateSyntaxError("{% related N [app_label.Model, ...] for object as var_name %}")

    if not bits[1].isdigit():
        raise template.TemplateSyntaxError("Count must be an integer.")

    if bits[-2] != 'as':
        raise template.TemplateSyntaxError("Tag must end with as var_name ")
    if bits[-4] != 'for':
        raise template.TemplateSyntaxError("Tag must end with for object as var_name ")

    if '.' in bits[2] or bits[2] == 'for':
        mod_index = 2
        finder = None
    else:
        mod_index = 3
        finder = bits[2]

    mods = []
    for m in bits[mod_index:-4]:
        if m == ',':
            continue
        if ',' in m:
            ms = m.split(',')
            for msm in ms:
                if not msm:
                    continue
                try:
                    mods.append(get_model(*msm.split('.')))
                except:
                    raise template.TemplateSyntaxError("%r doesn't represent any model." % msm)
        else:
            try:
                mods.append(get_model(*m.split('.')))
            except:
                raise template.TemplateSyntaxError("%r doesn't represent any model." % m)

    return bits[-3], int(bits[1]), bits[-1], mods, finder
Beispiel #5
0
def _parse_box(nodelist, bits):
    # {% box BOXTYPE for var_name %}                {% box BOXTYPE for content.type with PK_FIELD PK_VALUE %}
    if (len(bits) != 4 or bits[2] != 'for') and (len(bits) != 7 or bits[2] != 'for' or bits[4] != 'with'):
        raise template.TemplateSyntaxError, "{% box BOXTYPE for content.type with FIELD VALUE %} or {% box BOXTYPE for var_name %}"

    if len(bits) == 4:
        # var_name
        return BoxNode(bits[1], nodelist, var=template.Variable(bits[3]))
    else:
        try:
            model = get_model(*bits[3].split('.'))
        except LookupError:
            model = None
        if model is None:
            return EmptyNode()

        lookup_val = template.Variable(bits[6])
        try:
            lookup_val = lookup_val.resolve({})
        except template.VariableDoesNotExist:
            pass
        return BoxNode(bits[1], nodelist, model=model, lookup=(smart_str(bits[5]), lookup_val))
Beispiel #6
0
def _get_key(start, model, pk=None, version_key=False, **kwargs):
    Publishable = get_model('core', 'publishable')
    if issubclass(model.model_class(), Publishable) and model.model_class() != Publishable:
        model = ContentType.objects.get_for_model(Publishable)

    if pk and not kwargs:
        key = ':'.join((
            start, str(model.pk), str(pk)
        ))
        if version_key:
            return key + ':VER'
        version = cache.get(key + ':VER') or '0'
        return '%s:%s' % (key, version)

    for key, val in six.iteritems(kwargs):
        if hasattr(val, 'pk'):
            kwargs[key] = val.pk

    return normalize_key(':'.join((
                start,
                str(model.pk),
                ','.join(':'.join((key, smart_str(kwargs[key]).replace(' ', '_'))) for key in sorted(kwargs.keys()))
    )))
Beispiel #7
0
def listing_parse(input):
    params = {}
    if len(input) < 4:
        raise template.TemplateSyntaxError("%r tag argument should have at least 4 arguments" % input[0])
    o = 1
    # limit
    params["count"] = template.Variable(input[o])
    o = 2

    params["category"] = Category.objects.get_by_tree_path("")
    while o < len(input):
        # offset
        if input[o] == "from":
            params["offset"] = template.Variable(input[o + 1])
            o = o + 2

        # from - models definition
        elif input[o] == "of":
            o = o + 1
            mods = []
            while input[o] not in LISTING_PARAMS:
                mods.append(input[o])
                o += 1

            l = []
            for mod in "".join(mods).split(","):
                m = get_model(*mod.split("."))
                if m is None:
                    raise template.TemplateSyntaxError(
                        "%r tag cannot list objects of unknown model %r" % (input[0], mod)
                    )
                l.append(ContentType.objects.get_for_model(m))
            params["content_types"] = l

        # for - category definition
        elif input[o] == "for":
            params["category"] = template.Variable(input[o + 1])
            o = o + 2

        # with
        elif input[o] == "with":
            o = o + 1
            if input[o] == "children":
                params["children"] = ListingHandler.IMMEDIATE
            elif input[o] == "descendents":
                params["children"] = ListingHandler.ALL
            else:
                raise template.TemplateSyntaxError(
                    "%r tag's argument 'with' required specification (with children|with descendents)" % input[0]
                )
            o = o + 1

        # without (exclude publishable
        elif input[o] == "without":
            params["exclude"] = template.Variable(input[o + 1])
            o = o + 2

        # using (isting handlers)
        elif input[o] == "using":
            params["source"] = template.Variable(input[o + 1])
            o = o + 2

        # as
        elif input[o] == "as":
            var_name = input[o + 1]
            o = o + 2
            break
        else:
            raise template.TemplateSyntaxError("Unknown param for %s: %r" % (input[0], input[o]))
    else:
        raise template.TemplateSyntaxError("%r tag requires 'as' argument" % input[0])

    if o < len(input):
        raise template.TemplateSyntaxError("%r tag requires 'as' as last argument" % input[0])

    return var_name, params
Beispiel #8
0
def listing_parse(input):
    params = {}
    if len(input) < 4:
        raise template.TemplateSyntaxError, "%r tag argument should have at least 4 arguments" % input[0]
    o = 1
    # limit
    params['count'] = template.Variable(input[o])
    o = 2

    params['category'] = Category.objects.get_by_tree_path('')
    while o < len(input):
        # offset
        if input[o] == 'from':
            params['offset'] = template.Variable(input[o + 1])
            o = o + 2

        # from - models definition
        elif input[o] == 'of':
            o = o + 1
            mods = []
            while input[o] not in LISTING_PARAMS:
                mods.append(input[o])
                o += 1

            l = []
            for mod in ''.join(mods).split(','):
                m = get_model(*mod.split('.'))
                if m is None:
                    raise template.TemplateSyntaxError, "%r tag cannot list objects of unknown model %r" % (input[0], mod)
                l.append(ContentType.objects.get_for_model(m))
            params['content_types'] = l

        # for - category definition
        elif input[o] == 'for':
            params['category'] = template.Variable(input[o + 1])
            o = o + 2

        # with
        elif input[o] == 'with':
            o = o + 1
            if input[o] == 'children':
                params['children'] = ListingHandler.IMMEDIATE
            elif input[o] == 'descendents':
                params['children'] = ListingHandler.ALL
            else:
                raise template.TemplateSyntaxError, "%r tag's argument 'with' required specification (with children|with descendents)" % input[0]
            o = o + 1

        # without (exclude publishable
        elif input[o] == 'without':
            params['exclude'] = template.Variable(input[o + 1])
            o = o + 2

        # using (isting handlers)
        elif input[o] == 'using':
            params['source'] = template.Variable(input[o + 1])
            o = o + 2

        # as
        elif input[o] == 'as':
            var_name = input[o + 1]
            o = o + 2
            break
        else:
            raise template.TemplateSyntaxError('Unknown param for %s: %r' % (input[0], input[o]))
    else:
        raise template.TemplateSyntaxError, "%r tag requires 'as' argument" % input[0]

    if o < len(input):
        raise template.TemplateSyntaxError, "%r tag requires 'as' as last argument" % input[0]

    return var_name, params
Beispiel #9
0
 def _get_listing(self, publishable, score):
     Listing = get_model('core', 'listing')
     publish_from = from_timestamp(score)
     return Listing(publishable=publishable, category=publishable.category, publish_from=publish_from)
Beispiel #10
0
def ListingHandlerClass():
    return get_model('core', 'Listing').objects.get_listing_handler(core_settings.REDIS_LISTING_HANDLER)
Beispiel #11
0
 def _get_listing(self, publishable, score):
     Listing = get_model('core', 'listing')
     return Listing(publishable=publishable, category=publishable.category)
Beispiel #12
0
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE):
    """
    Return a list of objects with given PKs using cache.

    Params:
        pks - list of Primary Key values to look up or list of content_type_id, pk tuples
        model - ContentType instance representing the model's class or the model class itself
        timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT

    Throws:
        model.DoesNotExist is propagated from content_type.get_object_for_this_type
    """
    if model is not None:
        if not isinstance(model, ContentType):
            model = ContentType.objects.get_for_model(model)
        pks = [(model, pk) for pk in pks]
    else:
        pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks]

    keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks]

    cached = cache.get_many(keys)

    # keys not in cache
    keys_to_set = set(keys) - set(cached.keys())
    if keys_to_set:
        # build lookup to get model and pks from the key
        lookup = dict(zip(keys, pks))

        to_get = {}
        # group lookups by CT so we can do in_bulk
        for k in keys_to_set:
            ct, pk = lookup[k]
            to_get.setdefault(ct, {})[int(pk)] = k

        # take out all the publishables
        publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable'))
        if publishable_ct in to_get:
            publishable_keys = to_get.pop(publishable_ct)
            models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys())
            for m in models:
                ct = ContentType.objects.get_for_id(m['content_type_id'])
                pk = m['id']
                # and put them back as their native content_type
                to_get.setdefault(ct, {})[pk] = publishable_keys[pk]

        to_set = {}
        # retrieve all the models from DB
        for ct, vals in to_get.items():
            models = ct.model_class()._default_manager.in_bulk(vals.keys())
            for pk, m in models.items():
                k = vals[pk]
                cached[k] = to_set[k] = m

        if not isinstance(cache, DummyCache):
            # write them into cache
            cache.set_many(to_set, timeout=timeout)

    out = []
    for k in keys:
        try:
            out.append(cached[k])
        except KeyError:
            if missing == NONE:
                out.append(None)
            elif missing == SKIP:
                pass
            elif missing == RAISE:
                ct = ContentType.objects.get_for_id(int(k.split(':')[1]))
                raise ct.model_class().DoesNotExist(
                    '%s matching query does not exist.' % ct.model_class()._meta.object_name)
    return out