Tastypie using the cache for list data is not an issue

Source: Internet
Author: User
Tags serialization install redis

This is the first blog, my eldest brother Chen Rujie (a very cool programmer) said, only the things they have researched can be written on the blog, I would like to follow the teachings.

Environment: django==1.8.2, Django-tastypie==0.12.2-dev, redis==2.10.3, django-redis==4.1.0

Django is configured to use Redis as the background cache

Install the Redis-server (sudo apt-get install redis-server) in Ubuntu and add the following configuration to the Django settings: (Refer to the Http://niwinz.github.io /django-redis/latest/)

# to set Django's default cache add by Minkedongcaches = {"Default": {"backend": "Django_redis.cache.RedisCach E "," Location ":" REDIS://127.0.0.1:6379/1 "," Options ": {" Client_class ":" Django_redis.client.Def Aultclient ",}}}

When writing Tastypie's own modelresource, add in meta:

Cache = Simplecache (timeout=8*60*60)

When I request this modelresource, make a GET Request "/api/v1/author/1/", use the command in Ubuntu Bash: redis-cli-n 1 into Redis, type the command in Redis: Keys *, Check to see that the request results for this API have been cached.

But when I issued a GET request "/api/v1/author/", I went into Redis view and found that my results were not cached.

Decisively into the Tastypie source view, in the "Tastypie.resources.ModelResource" in the following two methods:

    def get_list (Self, request, **kwargs):          "" "        returns a serialized list  of resources.        Calls  ' Obj_get_list '  to  provide the data, then handles that result         set and serializes it.        should  return a HttpResponse  (200 ok) .         "" "         # TODO: Uncached for now.  invalidation that works for everyone may be         #       impossible.         base_bundle = self.bUild_bundle (request=request)         objects = self.obj_get_ List (Bundle=base_bundle, **self.remove_api_resource_names (Kwargs))          sorted_objects = self.apply_sorting (objects, options=request. GET)         paginator = self._meta.paginator_class (request. Get, sorted_objects, resource_uri=self.get_resource_uri (),  limit=self._meta.limit, max_ Limit=self._meta.max_limit, collection_name=self._meta.collection_name)          to_be_serialized = paginator.page ()          # Dehydrate the bundles in preparation for serialization.         bundles = []        for  obj in to_be_serialized[self._meta.collection_name]:            bundle =  Self.build_bundle (obj=obj, request=request)              bundles.append (Self.full_dehydrate (bundle, for_list=true))          to_be_serialized[self._meta.collection_name] = bundles         to_be_serialized = self.alter_list_data_to_serialize (Request, to_be_ Serialized)         return self.create_response (request, to_ be_serialized)             def get_detail (self ,  request, **kwargs):         "" "         Returns a single serialized resource.         Calls ' Cached_obj_get/obj_get '  to provide the data, then handles that  result        set and serializes it.         Should return a HttpResponse  (200 ok) .          "" "        basic_bundle =  self.build_bundle (request=request)         try:             obj = self.cached_obj_get (Bundle=basic_bundle,  **self.remove_api_resource_names (Kwargs))         except  Objectdoesnotexist:            return http. Httpnotfound ()         except MultipleObjectsReturned:              return http. Httpmultiplechoices ("More than one resource is found at this uri.")         bundle = self.build_bundle (obj=obj, request= Request)         bundle = self.full_dehydrate (bundle)          bundle = self.alter_detail_data_to_serialize (Request,  bundle)         return self.create_response (request,  Bundle

Using the PDB break point, found "/api/v1/author/1/" Request call Get_detail method, and "/api/v1/author/" Request call Get_list method, from the source is not difficult to see, Get_detail called Cached_ Obj_get method, which takes data from the cache, and Get_list calls the Obj_get_list method (there is a cached_obj_get_list method in the source code, which is not called), that is, the data is not taken from the cache (in fact get_ An explanation has been given in the comments of the list method

# todo:uncached for now. Invalidation that works for everyone will be impossible.), OK, the solution is simpler, just cover it in your own modelresource and change it to:

   def get_list (Self, request, **kwargs):          "" "        Returns a serialized list  of resources.        calls  ' Obj_get_list '  to  provide the data, then handles that result         set and serializes it.        Should  return a httpresponse  (200 ok) .         "" "         # todo: uncached for now. invalidation  that works for everyone may be        #        impossible.        base_ Bundle = self.build_bUndle (request=request)         objects = self.cached_obj_get_ List (Bundle=base_bundle, **self.remove_api_resource_names (Kwargs))          sorted_objects = self.apply_sorting (objects, options=request. GET)         paginator = self._meta.paginator_class (request. Get, sorted_objects, resource_uri=self.get_resource_uri (),  limit=self._meta.limit, max_ Limit=self._meta.max_limit, collection_name=self._meta.collection_name)          to_be_serialized = paginator.page ()          # Dehydrate the bundles in preparation for serialization.         bundles = []        for  obj in to_be_serialized[self._meta.collection_name]:            bundle =  Self.build_bundle (obj=obj, request=request)              bundles.append (Self.full_dehydrate (bundle, for_list=true))          to_be_serialized[self._meta.collection_name] = bundles         to_be_serialized = self.alter_list_data_to_serialize (Request, to_be_ Serialized)         return self.create_response (request, to_ be_serialized)

After requesting "/api/v1/author/" again, it is discovered that the result has been cached in Redis!

Because the mechanism of REDIS is not well understood, the latter will study the Redis things, what errors, welcome to correct me!

This article is from the "7673365" blog, please be sure to keep this source http://7683365.blog.51cto.com/7673365/1675359

Tastypie using the cache for list data is not an issue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.