diff --git a/model_cache/model_cache.py b/model_cache/model_cache.py index 78cba6e..cb67303 100644 --- a/model_cache/model_cache.py +++ b/model_cache/model_cache.py @@ -41,17 +41,7 @@ class OriginalClass(): pass # so we can setattr here. _model_cache.__name__ = decorated_class.__name__ _model_cache.__module__ = decorated_class.__module__ # so can pickle :) - dbpath = None - if _model_cache.original.cache_dir: - dbpath = os.path.join(_model_cache.original.cache_dir, \ - repr(_model_cache).split("'")[1].split(".")[-1] + ".db") - - _model_cache.datadict = { - "memory" : ModelCacheStoreMemory, - "sqlite" : ModelCacheStoreSqlite, - "redis" : ModelCacheStoreRedis, - }[_model_cache.original.storage_type](dbpath) - print "[ModelCache] Init at %s" % (dbpath or '[memory]') + _model_cache.connect() return _model_cache return _model_cache_decorator diff --git a/model_cache/model_cache_class.py b/model_cache/model_cache_class.py index 158b40d..0ae2c6f 100644 --- a/model_cache/model_cache_class.py +++ b/model_cache/model_cache_class.py @@ -42,6 +42,25 @@ def has_item_id(self, record): """ Detect if there is an item_id, which should be already wrote to database """ raise NotImplemented + @classmethod + def connect(cls): cls.reconnect(is_reconnect=False) + + @classmethod + def reconnect(cls, is_reconnect=True): + dbpath = None + if cls.original.cache_dir: + dbpath = os.path.join(cls.original.cache_dir, \ + repr(cls).split("'")[1].split(".")[-1] + ".db") + + cls.datadict = { + "memory" : ModelCacheStoreMemory, + "sqlite" : ModelCacheStoreSqlite, + "redis" : ModelCacheStoreRedis, + }[cls.original.storage_type](dbpath) + + msg = 'Reconnect' if is_reconnect else 'Init' + print "[ModelCache] %s at %s" % (msg, dbpath or '[memory]') + @classmethod def build_indexes(cls, items=[]): # items 必定是list, 经过cPickle反序列化回来的