def get_photo_in_format(self, photo, format): if isinstance(photo, Photo): photo_id = photo.id else: photo_id = photo photo = None if not isinstance(format, Format): format = Format.objects.get_for_name(format) if redis: p = redis.pipeline() p.hgetall(REDIS_PHOTO_KEY % photo_id) p.hgetall(REDIS_FORMATTED_PHOTO_KEY % (photo_id, format.id)) original, formatted = p.execute() if formatted: formatted['original'] = original return formatted if not photo: try: photo = get_cached_object(Photo, pk=photo_id) except Photo.DoesNotExist: return format.get_blank_img() try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=format) except FormatedPhoto.DoesNotExist: try: # use get or create because there is a possible race condition here # we don't want to JUST use get_or_create to go through cache 99.9% of the time formated_photo, _ = self.get_or_create(photo=photo, format=format) except (IOError, SystemError), e: log.warning("Cannot create formatted photo due to %s.", e) return format.get_blank_img()
def img(parser, token): """ Examples: {% img FORMAT for VAR as VAR_NAME %} {% img FORMAT with FIELD VALUE as VAR_NAME %} """ bits = token.split_contents() if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" try: format = get_cached_object(Format, name=bits[1], sites__id=settings.SITE_ID) except Format.DoesNotExist: logmsg = "Format with name %r does not exist (for site id %d)" % ( bits[1], settings.SITE_ID) log.error(logmsg) if not settings.TEMPLATE_DEBUG: return template.Node() raise template.TemplateSyntaxError(logmsg) if len(bits) == 6: # img FORMAT for VAR_NAME if bits[2] != 'for': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %}" formated_photo = bits[3] elif len(bits) == 7: # img FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% img FORMAT with FIELD VALUE as VAR_NAME %}" try: photo = get_cached_object(Photo, **{str(bits[3]): bits[4]}) except photo.DoesNotExist: raise template.TemplateSyntaxError, "Photo with %r of %r does not exist" % ( bits[3], bits[4]) try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=format) except FormatedPhoto.DoesNotExist: formated_photo = FormatedPhoto.objects.create(photo=photo, format=format) else: raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" return ImgTag(formated_photo, format, bits[-1])
def format_photo_json(self, request, photo, format): "Used in admin image 'crop tool'." try: photo = get_cached_object(Photo, pk=photo) format = get_cached_object(Format, pk=format) content = { "error": False, "image": settings.MEDIA_URL + photo.image, "width": photo.width, "height": photo.height, "format_width": format.max_width, "format_height": format.max_height, } except (Photo.DoesNotExist, Format.DoesNotExist): content = {"error": True} return HttpResponse(simplejson.dumps(content))
def render(self, context): unique_var_name = None for key in self.parameters_to_resolve: if key == 'unique': unique_var_name = self.parameters[key] if key == 'unique' and unique_var_name not in context.dicts[ -1]: # autocreate variable in context self.resolved_parameters[key] = context.dicts[-1][ unique_var_name] = set() continue #self.parameters[key] = template.Variable(self.parameters[key]).resolve(context) self.resolved_parameters[key] = self.resolve_parameter( key, context) if self.resolved_parameters.has_key('category') and \ isinstance(self.resolved_parameters['category'], basestring): self.resolved_parameters['category'] = get_cached_object( Category, tree_path=self.resolved_parameters['category'], site__id=settings.SITE_ID) out = Listing.objects.get_listing(**self.resolved_parameters) if 'unique' in self.parameters: unique = self.resolved_parameters[ 'unique'] #context[unique_var_name] map(lambda x: unique.add(x.placement_id), out) context[self.var_name] = out return ''
def __get__(self, instance, instance_type=None): # Fix for django 1.0 Admin Validation if instance is None: # TODO: hotfixed #raise AttributeError, u"%s must be accessed via instance" % self.name return try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None # Make sure to use ContentType.objects.get_for_id() to ensure that # lookups are cached (see ticket #5570). This takes more code than # the naive ``getattr(instance, self.ct_field)``, but has better # performance when dealing with GFKs in loops and such. f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) if ct_id: ct = self.get_content_type(id=ct_id) try: rel_obj = get_cached_object(ct, pk=getattr( instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj
def _parse_img(bits): if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" try: format = Format.objects.get_for_name(bits[1]) except Format.DoesNotExist: logmsg = "Format with name %r does not exist (for site id %d)" % (bits[1], settings.SITE_ID) log.error(logmsg) if not settings.TEMPLATE_DEBUG: return template.Node() raise template.TemplateSyntaxError(logmsg) if len(bits) == 6: # img FORMAT for VAR_NAME if bits[2] != 'for': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %}" formated_photo = bits[3] elif len(bits) == 7: # img FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% img FORMAT with FIELD VALUE as VAR_NAME %}" try: photo = get_cached_object(Photo, **{str(bits[3]) : bits[4]}) except photo.DoesNotExist: raise template.TemplateSyntaxError, "Photo with %r of %r does not exist" % (bits[3], bits[4]) formated_photo = FormatedPhoto.objects.get_photo_in_format(photo, format) else: raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" return ImgTag(formated_photo, format, bits[-1])
def test_get_publishable_returns_subclass(self): create_basic_categories(self) create_and_place_a_publishable(self) tools.assert_equals( self.publishable, utils.get_cached_object(Publishable, pk=self.publishable.pk))
def format_photo_json(request, photo, format): "Used in admin image 'crop tool'." try: photo = get_cached_object(Photo, pk=photo) format = get_cached_object(Format, pk=format) content = { 'error': False, 'image': settings.MEDIA_URL + photo.image, 'width': photo.width, 'height': photo.height, 'format_width': format.max_width, 'format_height': format.max_height } except (Photo.DoesNotExist, Format.DoesNotExist): content = {'error': True} return HttpResponse(simplejson.dumps(content))
def __get__(self, instance, instance_type=None): # Fix for django 1.0 Admin Validation if instance is None: # TODO: hotfixed #raise AttributeError, u"%s must be accessed via instance" % self.name return try: return getattr(instance, self.cache_attr) except AttributeError: rel_obj = None # Make sure to use ContentType.objects.get_for_id() to ensure that # lookups are cached (see ticket #5570). This takes more code than # the naive ``getattr(instance, self.ct_field)``, but has better # performance when dealing with GFKs in loops and such. f = self.model._meta.get_field(self.ct_field) ct_id = getattr(instance, f.get_attname(), None) if ct_id: ct = self.get_content_type(id=ct_id) try: rel_obj = get_cached_object(ct, pk=getattr(instance, self.fk_field)) except ObjectDoesNotExist: pass setattr(instance, self.cache_attr, rel_obj) return rel_obj
def get_obj(self, context): if self.model and self.lookup: if isinstance(self.lookup[1], template.Variable): try: lookup_val = self.lookup[1].resolve(context) except template.VariableDoesNotExist as e: log.warning("BoxNode: Template variable does not exist. var_name=%s", self.lookup[1].var) raise ObjectNotFoundOrInvalid() else: lookup_val = self.lookup[1] try: obj = get_cached_object(self.model, **{self.lookup[0]: lookup_val}) except (models.ObjectDoesNotExist, AssertionError) as e: log.warning("BoxNode: %s (%s : %s)", str(e), self.lookup[0], lookup_val) raise ObjectNotFoundOrInvalid() else: try: obj = self.var.resolve(context) except template.VariableDoesNotExist as e: log.warning("BoxNode: Template variable does not exist. var_name=%s", self.var.var) raise ObjectNotFoundOrInvalid() if not obj: raise ObjectNotFoundOrInvalid() return obj
def get_for_name(self, name): try: return FORMAT_CACHE[name] except KeyError: FORMAT_CACHE[name] = format = get_cached_object( Format, name=name, sites__id=settings.SITE_ID) return format
def format_photo_json(self, request, photo, format): "Used in admin image 'crop tool'." try: photo = get_cached_object(Photo, pk=photo) format = get_cached_object(Format, pk=format) content = { 'error': False, 'image':settings.MEDIA_URL + photo.image, 'width':photo.width, 'height': photo.height, 'format_width':format.max_width, 'format_height':format.max_height } except (Photo.DoesNotExist, Format.DoesNotExist): content = {'error':True} return HttpResponse(json.dumps(content))
def _parse_img(bits, legacy=True): if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" try: format = Format.objects.get_for_name(bits[1]) except Format.DoesNotExist: logmsg = "Format with name %r does not exist (for site id %d)" % (bits[1], settings.SITE_ID) log.error(logmsg) if not settings.TEMPLATE_DEBUG: return template.Node() raise template.TemplateSyntaxError(logmsg) if len(bits) == 6: # img FORMAT for VAR_NAME if bits[2] != 'for': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %}" formated_photo = bits[3] elif len(bits) == 7: # img FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% img FORMAT with FIELD VALUE as VAR_NAME %}" try: photo = get_cached_object(Photo, **{str(bits[3]) : bits[4]}) except photo.DoesNotExist: raise template.TemplateSyntaxError, "Photo with %r of %r does not exist" % (bits[3], bits[4]) formated_photo = FormatedPhoto.objects.get_photo_in_format(photo, format) else: raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" return ImgTag(formated_photo, format, bits[-1])
def test_save_invalidates_object(self): self.ct = ContentType.objects.get_for_model(ContentType) ct = utils.get_cached_object(self.ct, pk=self.ct.pk) tools.assert_equals(ct, self.ct) tools.assert_equals(self.ct, self.cache.get(utils._get_key(utils.KEY_PREFIX, self.ct, pk=self.ct.pk))) self.ct.save() tools.assert_equals(None, self.cache.get(utils._get_key(utils.KEY_PREFIX, self.ct, pkr=self.ct.pk)))
def thumb_format(self): if not hasattr(self, '_thumb_format'): if not hasattr(settings, 'PHOTOS_THUMB_FORMAT'): self._thumb_format = None else: self._thumb_format = get_cached_object(Format, id=settings.PHOTOS_THUMB_FORMAT) return self._thumb_format
def img(parser, token): """ Examples: {% img FORMAT for VAR as VAR_NAME %} {% img FORMAT with FIELD VALUE as VAR_NAME %} """ bits = token.split_contents() if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" try: format = get_cached_object(Format, name=bits[1], sites__id=settings.SITE_ID) except Format.DoesNotExist: logmsg = "Format with name %r does not exist (for site id %d)" % (bits[1], settings.SITE_ID) log.error(logmsg) if not settings.TEMPLATE_DEBUG: return template.Node() raise template.TemplateSyntaxError(logmsg) if len(bits) == 6: # img FORMAT for VAR_NAME if bits[2] != 'for': raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %}" formated_photo = bits[3] elif len(bits) == 7: # img FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% img FORMAT with FIELD VALUE as VAR_NAME %}" try: photo = get_cached_object(Photo, **{str(bits[3]) : bits[4]}) except photo.DoesNotExist: raise template.TemplateSyntaxError, "Photo with %r of %r does not exist" % (bits[3], bits[4]) try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=format) except FormatedPhoto.DoesNotExist: formated_photo = FormatedPhoto.objects.create(photo=photo, format=format) else: raise template.TemplateSyntaxError, "{% img FORMAT for VAR as VAR_NAME %} or {% img FORMAT with FIELD VALUE as VAR_NAME %}" return ImgTag(formated_photo, format, bits[-1])
def thumb_format(self): if not hasattr(self, '_thumb_format'): if not hasattr(settings, 'PHOTOS_THUMB_FORMAT'): self._thumb_format = None else: self._thumb_format = get_cached_object( Format, id=settings.PHOTOS_THUMB_FORMAT) return self._thumb_format
def media(parser, token): """ Examples: {% media FORMAT for VAR as VAR_NAME %} {% media FORMAT with FIELD VALUE as VAR_NAME %} """ bits = token.split_contents() if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %} or {% media FORMAT with FIELD VALUE as VAR_NAME %}" try: format = get_cached_object(Format, name=bits[1]) except Format.DoesNotExist: raise template.TemplateSyntaxError, "Format with name %r does not exist" % bits[ 1] if len(bits) == 6: # media FORMAT for VAR if bits[2] != 'for': raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %}" formatted_media = bits[3] elif len(bits) == 7: # media FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% media FORMAT with FIELD VALUE as VAR_NAME %}" try: media = get_cached_object(Media, **{str(bits[3]): bits[4]}) except media.DoesNotExist: raise template.TemplateSyntaxError, "Media with %r of %r does not exist" % ( bits[3], bits[4]) try: formatted_media = get_cached_object(Target, source=media.file, format=format) except Target.DoesNotExist: raise template.TemplateSyntaxError, "Format %r for media with %r of %r does not exist" % ( bits[1], bits[3], bits[4]) else: raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %} or {% media FORMAT with FIELD VALUE as VAR_NAME %}" return MediaTag(formatted_media, format, bits[-1])
def thumb_url(request, photo): try: photo = get_cached_object(Photo, pk=photo) url = photo.thumb_url() if not url: url = '' content = {'url': url} except (Photo.DoesNotExist): content = {'url': '', 'does_not_exist': True} return HttpResponse(simplejson.dumps(content))
def get_thumb_format(): global _thumb_format from ella.photos.models import Format if _thumb_format == '--unset--': if not hasattr(newman_settings, 'PHOTOS_THUMB_FORMAT'): _thumb_format = None else: _thumb_format = get_cached_object(Format, name=newman_settings.PHOTOS_THUMB_FORMAT) return _thumb_format
def get_thumb_format(): global _thumb_format from ella.photos.models import Format if _thumb_format == '--unset--': if not hasattr(newman_settings, 'PHOTOS_THUMB_FORMAT'): _thumb_format = None else: _thumb_format = get_cached_object( Format, name=newman_settings.PHOTOS_THUMB_FORMAT) return _thumb_format
def items(self, obj): kwa = {} if isinstance(obj, tuple): category, content_type = obj kwa['content_types'] = [ content_type ] kwa['category'] = category elif obj: kwa['category'] = obj else: kwa['category'] = get_cached_object(Category, tree_parent__isnull=True, site__id=settings.SITE_ID) return Listing.objects.get_listing(count=NUM_IN_FEED, **kwa)
def get_formated_photo(self, format): "Return formated photo" format_object = Format.objects.get(name=format, sites=settings.SITE_ID) try: formated_photo = get_cached_object(FormatedPhoto, photo=self, format=format_object) except FormatedPhoto.DoesNotExist: try: formated_photo = FormatedPhoto.objects.create(photo=self, format=format_object) except (IOError, SystemError, IntegrityError): return None return formated_photo
def get_photo_in_format(self, photo, format, include_original=True): if isinstance(photo, Photo): photo_id = photo.id else: photo_id = photo photo = None if not isinstance(format, Format): format = Format.objects.get_for_name(format) if redis: p = redis.pipeline() p.hgetall(REDIS_PHOTO_KEY % photo_id) p.hgetall(REDIS_FORMATTED_PHOTO_KEY % (photo_id, format.id)) original, formatted = p.execute() if formatted: if include_original: formatted['original'] = original return formatted if not photo: try: photo = get_cached_object(Photo, pk=photo_id) except Photo.DoesNotExist: return format.get_blank_img() try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=format) except FormatedPhoto.DoesNotExist: try: # use get or create because there is a possible race condition here # we don't want to JUST use get_or_create to go through cache 99.9% of the time formated_photo, _ = self.get_or_create(photo=photo, format=format) except (IOError, SystemError), e: log.warning("Cannot create formatted photo due to %s.", e) return format.get_blank_img()
def media(parser, token): """ Examples: {% media FORMAT for VAR as VAR_NAME %} {% media FORMAT with FIELD VALUE as VAR_NAME %} """ bits = token.split_contents() if len(bits) < 2 or bits[-2] != 'as': raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %} or {% media FORMAT with FIELD VALUE as VAR_NAME %}" try: format = get_cached_object(Format, name=bits[1]) except Format.DoesNotExist: raise template.TemplateSyntaxError, "Format with name %r does not exist" % bits[1] if len(bits) == 6: # media FORMAT for VAR if bits[2] != 'for': raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %}" formatted_media = bits[3] elif len(bits) == 7: # media FORMAT with FIELD VALUE if bits[2] != 'with': raise template.TemplateSyntaxError, "{% media FORMAT with FIELD VALUE as VAR_NAME %}" try: media = get_cached_object(Media, **{str(bits[3]) : bits[4]}) except media.DoesNotExist: raise template.TemplateSyntaxError, "Media with %r of %r does not exist" % (bits[3], bits[4]) try: formatted_media = get_cached_object(Target, source=media.file, format=format) except Target.DoesNotExist: raise template.TemplateSyntaxError, "Format %r for media with %r of %r does not exist" % (bits[1], bits[3], bits[4]) else: raise template.TemplateSyntaxError, "{% media FORMAT for VAR as VAR_NAME %} or {% media FORMAT with FIELD VALUE as VAR_NAME %}" return MediaTag(formatted_media, format, bits[-1])
def test_save_invalidates_object(self): self.ct = ContentType.objects.get_for_model(ContentType) ct = utils.get_cached_object(self.ct, pk=self.ct.pk) tools.assert_equals(ct, self.ct) tools.assert_equals( self.ct, self.cache.get( utils._get_key(utils.KEY_PREFIX, self.ct, pk=self.ct.pk))) self.ct.save() tools.assert_equals( None, self.cache.get( utils._get_key(utils.KEY_PREFIX, self.ct, pkr=self.ct.pk)))
def detail(request, category, url_remainder=''): path = category.split('/') # construct all possible tree_paths and get their IDs from redis part = [] pipe = redis.pipeline() for p in path: part.append(p) pipe.get(REDIS_KEY % '/'.join(part)) ids = pipe.execute() # no IDs -> 404 if not any(ids): raise Http404() # get the last ID == the most specific wiki object id = filter(None, ids)[-1] wiki = get_cached_object(Wiki, pk=id) if not (wiki.is_published() or wiki_settings.IS_MODERATOR_FUNC(request.user)): # future publish, render if accessed by moderator raise Http404() # treat the rest as part of custom_urls part leftover = category[len(wiki.tree_path):] object_rendering.send(sender=Wiki, request=request, category=wiki.category, publishable=wiki) context = { 'category': wiki.category, 'object': wiki, 'content_type': wiki.content_type, } # custom urls if leftover or url_remainder: url_remainder = ('%s/%s' % (leftover, url_remainder)). strip('/') + '/' return custom_urls.resolver.call_custom_view(request, wiki, url_remainder, context) # ella API response = render_as_api(request, wiki) if response: return response # custom detail if custom_urls.resolver.has_custom_detail(wiki): return custom_urls.resolver.call_custom_detail(request, context) object_rendered.send(sender=Wiki, request=request, category=wiki.category, publishable=wiki) return TemplateResponse(request, get_templates_from_publishable('object.html', wiki), context)
def get_for_path(self, path): """Returns a CategorySubdomain instance for a first part of the path if present in the database. """ path_items = [path_item for path_item in path.split('/') if len(path_item) > 0] result = None if (len(path_items) > 0): slug = path_items[0] try: result = get_cached_object(self.model, \ category__slug=slug, category__site__id=settings.SITE_ID) except self.model.DoesNotExist: pass return result
def get_object(self, bits): try: ct = get_content_type(bits[-1]) bits = bits[:-1] except (Http404, IndexError): ct = False if bits: cat = get_cached_object_or_404(Category, tree_path=u'/'.join(bits), site__id=settings.SITE_ID) else: cat = get_cached_object(Category, tree_parent__isnull=True, site__id=settings.SITE_ID) if ct: return (cat, ct) return cat
def render(self, context): if self.model and self.lookup: try: lookup_val = template.Variable(self.lookup[1]).resolve(context) except template.VariableDoesNotExist: lookup_val = self.lookup[1] try: obj = get_cached_object(self.model, **{self.lookup[0] : lookup_val}) except models.ObjectDoesNotExist, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) return '' except AssertionError, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) return ''
def get_formated_photo(self, format): "Return formated photo" format_object = Format.objects.get(name=format, sites=settings.SITE_ID) try: formated_photo = get_cached_object(FormatedPhoto, photo=self, format=format_object) except FormatedPhoto.DoesNotExist: try: formated_photo = FormatedPhoto.objects.create( photo=self, format=format_object) except (IOError, SystemError, IntegrityError): return None return formated_photo
def items(self, obj): kwa = {} if isinstance(obj, tuple): category, content_type = obj kwa['content_types'] = [ content_type ] kwa['category'] = category elif obj: kwa['category'] = obj else: kwa['category'] = get_cached_object(Category, tree_parent__isnull=True, site__id=settings.SITE_ID) # TODO: In ella based application children attr can be NONE, IMMEDIATE and ALL if kwa['category'].tree_parent != None: kwa['children'] = Listing.objects.ALL return Listing.objects.get_listing(count=core_settings.RSS_NUM_IN_FEED, **kwa)
def render(self, context): if isinstance(self.media, basestring): try: media = template.resolve_variable(self.media, context) except template.VariableDoesNotExist: return '' try: formatted_media = get_cached_object(Target, source=media.file, format=self.format) except Target.DoesNotExist: return '' else: formatted_media = self.media context[self.var_name] = formatted_media return ''
def render(self, context): if isinstance(self.photo, basestring): try: photo = template.Variable(self.photo).resolve(context) if not photo: return '' except template.VariableDoesNotExist: return '' try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=self.format) except FormatedPhoto.DoesNotExist: try: formated_photo = FormatedPhoto.objects.create(photo=photo, format=self.format) except (IOError, SystemError, IntegrityError), e: log.error("Cannot create formatted photo: %s" % e) context[self.var_name] = self.format.get_blank_img() return ''
def get_for_path(self, path): """Returns a CategorySubdomain instance for a first part of the path if present in the database. """ path_items = [ path_item for path_item in path.split('/') if len(path_item) > 0 ] result = None if (len(path_items) > 0): slug = path_items[0] try: result = get_cached_object(self.model, \ category__slug=slug, category__site__id=settings.SITE_ID) except self.model.DoesNotExist: pass return result
def get_obj(self, context=None): if self.model and self.lookup: if context: try: lookup_val = template.Variable(self.lookup[1]).resolve(context) except template.VariableDoesNotExist: lookup_val = self.lookup[1] else: lookup_val = self.lookup[1] try: obj = get_cached_object(self.model, **{self.lookup[0] : lookup_val}) except models.ObjectDoesNotExist, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) raise ObjectNotFoundOrInvalid() except AssertionError, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) raise ObjectNotFoundOrInvalid()
def render(self, context): unique_var_name = None for key in self.parameters_to_resolve: if key == 'unique': unique_var_name = self.parameters[key] if key == 'unique' and unique_var_name not in context.dicts[-1]: # autocreate variable in context self.parameters[key] = context.dicts[-1][ unique_var_name ] = set() continue self.parameters[key] = template.Variable(self.parameters[key]).resolve(context) if self.parameters.has_key('category') and isinstance(self.parameters['category'], basestring): self.parameters['category'] = get_cached_object(Category, tree_path=self.parameters['category'], site__id=settings.SITE_ID) out = Listing.objects.get_listing(**self.parameters) if 'unique' in self.parameters: unique = self.parameters['unique'] #context[unique_var_name] map(lambda x: unique.add(x.placement_id),out) context[self.var_name] = out return ''
def title(self, obj): if isinstance(obj, tuple): category, content_type = obj return _('Top %(count)d %(ctype)s objects in category %(cat)s.') % { 'count' : core_settings.RSS_NUM_IN_FEED, 'ctype' : content_type.model_class()._meta.verbose_name_plural, 'cat' : category.title } elif obj: return _('Top %(count)d objects in category %(cat)s.') % { 'count' : core_settings.RSS_NUM_IN_FEED, 'cat' : obj.title } else: obj = get_cached_object(Category, tree_parent__isnull=True, site__id=settings.SITE_ID) return _('Top %(count)d objects in category %(cat)s.') % { 'count' : core_settings.RSS_NUM_IN_FEED, 'cat' : obj.title }
def render(self, ctx): if self.tree_path == self.tree_path.strip('"'): try: root_cat = template.Variable(self.tree_path).resolve(ctx) except template.TemplateSyntaxError: return '' else: try: root_cat = get_cached_object(Category, tree_path=self.tree_path.strip('"'), site = settings.SITE_ID) except Category.DoesNotExist: return '' try: cats = Category.objects.filter(tree_parent=root_cat).order_by('title') if self.limit: cats = cats[:self.limit] ctx.update({self.varname: cats}) except Category.DoesNotExist: pass return ''
def render(self, context): if isinstance(self.photo, basestring): try: photo = template.Variable(self.photo).resolve(context) if not photo: return '' except template.VariableDoesNotExist: return '' try: formated_photo = get_cached_object(FormatedPhoto, photo=photo, format=self.format) except FormatedPhoto.DoesNotExist: try: formated_photo = FormatedPhoto.objects.create( photo=photo, format=self.format) except (IOError, SystemError, IntegrityError), e: log.error("Cannot create formatted photo: %s" % e) context[self.var_name] = self.format.get_blank_img() return ''
def render(self, context): try: obj = template.Variable(self.obj_var).resolve(context) except template.VariableDoesNotExist: return '' related = [] count = self.count # manually entered dependencies for rel in Related.objects.filter(source_ct=ContentType.objects.get_for_model(obj), source_id=obj._get_pk_val()): related.append(rel) count -= 1 if count <= 0: break # related objects vie tags if self.models and count > 0: from ella.tagging.models import TaggedItem for m in self.models: to_add = TaggedItem.objects.get_related(obj, m, count) for rel in to_add: if rel != obj and rel not in related: count -= 1 related.append(rel) if count <= 0: break # top objects in given category if count > 0: cat = get_cached_object(Category, pk=obj.category_id) listings = Listing.objects.get_listing(category=cat, count=count, mods=self.models) ext = [ listing.target for listing in listings if listing.target != obj ] related.extend(ext) count -= len(ext) if self.all_categories and count > 0: listings = Listing.objects.get_listing(count=count, mods=self.models) related.extend(listing.target for listing in listings if listing.target != obj) context[self.var_name] = related return ''
def get_obj(self, context): if self.model and self.lookup: if isinstance(self.lookup[1], template.Variable): try: lookup_val = self.lookup[1].resolve(context) except template.VariableDoesNotExist, e: log.warning( 'BoxNode: Template variable does not exist. var_name=%s', self.lookup[1].var) raise ObjectNotFoundOrInvalid() else: lookup_val = self.lookup[1] try: obj = get_cached_object(self.model, **{self.lookup[0]: lookup_val}) except (models.ObjectDoesNotExist, AssertionError), e: log.warning('BoxNode: %s (%s : %s)', str(e), self.lookup[0], lookup_val) raise ObjectNotFoundOrInvalid()
def get_obj(self, context=None): if self.model and self.lookup: if context: try: lookup_val = template.Variable( self.lookup[1]).resolve(context) except template.VariableDoesNotExist: lookup_val = self.lookup[1] else: lookup_val = self.lookup[1] try: obj = get_cached_object(self.model, **{self.lookup[0]: lookup_val}) except models.ObjectDoesNotExist, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) raise ObjectNotFoundOrInvalid() except AssertionError, e: log.error('BoxNode: %s (%s : %s)' % (str(e), self.lookup[0], lookup_val)) raise ObjectNotFoundOrInvalid()
def _get_template_list(self): " Get the hierarchy of templates belonging to the object/box_type given. " t_list = [] if hasattr(self.obj, 'category_id') and self.obj.category_id: from ella.core.models import Category cat = get_cached_object(Category, pk=self.obj.category_id) base_path = 'box/category/%s/content_type/%s.%s/' % (cat.path, self.app_label, self.module_name) if hasattr(self.obj, 'slug'): t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,)) t_list.append(base_path + '%s.html' % (self.box_type,)) t_list.append(base_path + 'box.html') base_path = 'box/content_type/%s.%s/' % (self.app_label, self.module_name) if hasattr(self.obj, 'slug'): t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,)) t_list.append(base_path + '%s.html' % (self.box_type,)) t_list.append(base_path + 'box.html') t_list.append('box/%s.html' % self.box_type) t_list.append('box/box.html') return t_list
def get_for_host(self, host): """Searches for a CategorySubdomain instance matching the first part of the domain. """ # split the domain into parts domain_parts = host.split('.') # prepare the default response result = None # process the domain if it is of the 3rd level or more if (len(domain_parts) > 2): # get the first part of the domain subdomain = domain_parts[0].lower() try: # get the category subdomain result = get_cached_object(self.model, \ subdomain_slug=subdomain, category__site__id=settings.SITE_ID) except self.model.DoesNotExist: # category subdomain does not exists pass return result
def test_get_publishable_returns_subclass(self): create_basic_categories(self) create_and_place_a_publishable(self) tools.assert_equals(self.publishable, utils.get_cached_object(Publishable, pk=self.publishable.pk))
def author(self): if self.is_authorized: user = get_cached_object(User, pk=self.user_id) return user.username return self.nickname
val = getattr(instance, self.field.attname) if val is None: # If NULL is an allowed value, return it. if self.field.null: return None raise self.field.rel.to.DoesNotExist rel_obj = retrieve_func(self.field.rel.to, val) setattr(instance, cache_name, rel_obj) return rel_obj CustomForeignKey.__name__ = name return CustomForeignKey CachedForeignKey = generate_fk_class('CachedForeignKey', lambda m, pk: get_cached_object(m, pk=pk)) def get_site(model, pk): try: return SITE_CACHE[pk] except KeyError: SITE_CACHE[pk] = get_cached_object(model, pk=pk) return SITE_CACHE[pk] SiteForeignKey = generate_fk_class('SiteForeignKey', get_site, Site) ContentTypeForeignKey = generate_fk_class( 'ContentTypeForeignKey', lambda m, pk: m._default_manager.get_for_id(pk), ContentType) CategoryForeignKey = generate_fk_class(
def get_site(model, pk): try: return SITE_CACHE[pk] except KeyError: SITE_CACHE[pk] = get_cached_object(model, pk=pk) return SITE_CACHE[pk]
def get_part_for_placement(self, placement): """ Return serie part for placement """ return get_cached_object(SeriePart, placement=placement)