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