Python:本地缓存localcache


Apache本地缓存文件:基于hashlib缓存
 
1.文件内容如下,localcache.py
# -*- coding: utf-8 -*-
#
# Copyright(c) 2010 poweredsites.org
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
 
import hashlib
from time import time
 
_mem_caches = {}
 
def mem_cache(expire=7200, key="", maxlen=100000,start=0):
    """Mem cache to python dict by key"""
    def wrapper(func):
        def mem_wrapped_func(*args, **kwargs):
            now = time()
            if key:
                c = key
            else:
                c = repr(func)
            k = key_gen(c, *args[start:], **kwargs)
 
            value = _mem_caches.get(k, None)
            if _valid_cache(value, now):
                return value["value"]
            else:
                val = func(*args, **kwargs)
                assert len(str(val))<=maxlen
                _mem_caches[k] = {"value":val, "expire":now+expire}
 
                return val
 
        return mem_wrapped_func
    return wrapper
 
def purge_mem():
    global _mem_caches
    count = len(_mem_caches)
    _mem_caches = {}
    return count
 
def key_gen(key, *args, **kwargs):
    code = hashlib.md5()
 
    code.update(str(key))
    code.update("".join(sorted(map(str, args))))
    code.update("".join(sorted(map(str, kwargs.iteritems()))))
 
    return code.hexdigest()
 
def _valid_cache(value, now):
    if value:
        if value["expire"] > now:
            return True
        else:
            return False
    else:
        return False
 
2.使用示例
(1) 缓存数据,在service/ebk5.py中:
from lib.localcache import mem_cache
class Ebk5BookService(object):
    @mem_cache(7200,'',1000000000)
    def  book_name_rel_id(self):
        '''
        书名与书籍ID映射关系
        '''
        bk_list = Ebk5Book.mgr(ismaster=True).raw("select bookName,ID from ebk5_book")
         return {i.get("bookName").lstrip('《').rstrip('》'):i.get("ID") for i in bk_list if i}
 
(2) 调用缓存数据,在service/ebk5.py中:
class Ebk5BookService(object):
     def get_id_by_name(self,name):
        '''
        根据书籍名称获取书籍ID
        '''
        book_id = 0
        bk_rel_dict = self. book_name_rel_id()
        if bk_rel_dict.has_key(str(name)):
            book_id = bk_rel_dict.get(str(name))
        return book_id


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM