从memcached中获取数据

时间:2017-07-17 06:55:13

标签: python memcached

我必须从memcached中获取数据。但我的代码是从数据库中获取它。

伪代码如下:

given a URL, try finding that page in the cache

if the page is in the cache:
   return the cached page
else:
   generate the page
   save the generated page in the cache (for next time)
   return the generated page

我的python代码如下:

class CachedAPIView(APIView):
    def get_queryset(self,request):
        return function(self,request.data)

    def get_object(self,queryset=None):
        obj = cache.get('%s-%s'%(self.modelName.lower(),self.kwargs['pk']),None)
        if not obj:
            obj=super(CachedAPIView,self).get_object(queryset)
            cache.set('%s-%s'%(self.modelName.lower(),self.kwargs['pk']),obj)

class ABC(CachedAPIView):
    def fun(self,request,format=None):  
        request.data['PubIp']=getUserIP(request)
        returnData=CachedAPIView.get_queryset(self,request)
        if returnData == "TOKEN_ERROR":#token error
            .....
        elif returnData == "RECORD_NOT_FOUND":#bad request
            ......
        else:
            ......

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

我已经尝试过这段代码并且有效。

import hashlib
import json
from django.core.cache import cache
from .views import *
class CacheService():
    def __init__(self, view=None, **kwargs):
        self.data = kwargs
        self.data.update({'view_name': view})
        self.key = self.prepare_key()
    def prepare_key(self):
        return hashlib.md5(json.dumps(self.data, sort_keys=True).encode('utf-8')).hexdigest()
    def set_to_cache(self, qs):
        cache.set(self.key, qs)
    def unset_cache(self, qs):
        cache.set(self.key, None)
    def delete_key_value(self):
        cache.delete(self.key)
    def get_from_cache(self):
        return cache.get(self.key, None)
    def clear_all_cache(self):
        cache.clear()

这是cache.py文件。要缓存的视图如下:

class MyView(APIView):
    def post(self,request,format=None):
        '''

        '''
        Data=my_function()
        cache_service = CacheService(qs_type='my_function()')
        event_queryset = cache_service.get_from_cache()
        if not event_queryset:
            event_queryset = my_function()
            cache_service.set_to_cache(event_queryset)
        if event_queryset == "TOKEN_ERROR":#token error
           ............
        elif event_queryset == "RECORD_NOT_FOUND":#bad request
            .............
        else:
            ......................