Example #1
0
 def update_cache(self, pk, key, value):
     cache = SimpleCache(self._meta.cache_key_format, self._meta.cache_duration,
                         lambda **kwargs: self(kwargs['pk']).to_dict())
     original = cache.get(pk=pk)
     if original:
         original[key] = value
         cache.set(original, pk=pk)
Example #2
0
    def serialize(self, resource_instance, options=None, request=None):
        """
        Serialize a resource instance. This method must return a json-convertible dictionary.
        This method use caches if available.
        """

        def load_cache(**_kwargs):
            return self.instance_to_python(resource_instance, exclude=self._meta.cache_ignored, options=options,
                                           request=request, **_kwargs)

        if self._meta.cache_key_format:
            cache = SimpleCache(self._meta.cache_key_format, self._meta.cache_duration, load_cache)
            ret = cache.get(pk=resource_instance._pk)
        else:
            ret = load_cache(pk=resource_instance._pk)
        if self._meta.cache_ignored:
            ret.update(self.instance_to_python(resource_instance,
                                               fields=self._meta.cache_ignored + self._meta.cache_ignored_virtual_only,
                                               request=request))
        elif self._meta.cache_ignored_virtual_only:
            ret.update(
                resource_instance.all_virtual_items(fields=self._meta.cache_ignored_virtual_only, request=request))
        if self._meta.filter_include or self._meta.filter_exclude:
            ret = recursive_dict_filter(ret, self._meta.filter_include, self._meta.filter_exclude)
        if options:
            if 'date_format' in options:
                is_timestamp_mode = options['date_format'] == 'F'
                if is_timestamp_mode:
                    for each in self._meta.date_format_fields:
                        if each in ret and ret[each]:
                            ret[each] = str(datetime.datetime.fromtimestamp(int(ret[each])))

        return ret