Back to index

nordugrid-arc-nox  1.1.0~rc6
cachedstringstore.py
Go to the documentation of this file.
00001 import arc
00002 import copy, os, base64
00003 
00004 from arcom.store.cachedpicklestore import CachedPickleStore
00005 
00006 from arcom.logger import Logger
00007 log = Logger(arc.Logger(arc.Logger_getRootLogger(), 'arcom.CachedStringStore'))
00008 
00009 class CachedStringStore(CachedPickleStore):
00010     """ Class for storing object in a serialized python format. """
00011 
00012     def __init__(self, storecfg, non_existent_object = {}):
00013         """ Constructor of CachedStringStore.
00014 
00015         StringStore(storecfg)
00016 
00017         'storecfg' is an XMLNode with a 'DataDir'
00018         'non_existent_object' will be returned if an object not found
00019         """
00020         CachedPickleStore.__init__(self, storecfg, non_existent_object)
00021         log.msg(arc.VERBOSE, "CachedStringStore constructor called")
00022         log.msg(arc.VERBOSE, "datadir:", self.datadir)
00023         self.store = {}
00024         self._load_storage()
00025 
00026     def _load_storage(self):
00027         filelist = self._list()
00028         for f in filelist:
00029             self.store[base64.b64decode(f)] = eval(file(os.path.join(self.datadir,f[:2],f), 'rb').read())
00030 
00031     def set(self, ID, object):
00032         """ Stores an object with the given ID..
00033 
00034         set(ID, object)
00035 
00036         'ID' is the ID of the object
00037         'object' is the object itself
00038         If there is already an object with this ID it will be overwritten completely.
00039         """
00040         if not ID:
00041             raise Exception, 'ID is empty'
00042         try:
00043             # generates a filename from the ID
00044             fn = self._filename(ID)
00045             tmp_fn = self._tmpfilename(ID)
00046             # if 'object' is empty, don't make file
00047             if object:
00048                 # serialize the given list into tmp_fn
00049                 f = file(tmp_fn,'wb')
00050                 f.write(str(object))
00051                 f.close()
00052                 # try to rename the file
00053                 try:
00054                     os.rename(tmp_fn,fn)
00055                 except:
00056                     # try to create parent dir first, then rename the file
00057                     os.mkdir(os.path.dirname(fn))
00058                     os.rename(tmp_fn,fn)
00059                 self.store[ID] = object
00060             elif os.path.isfile(fn):
00061                 # object empty, file is not needed anymore
00062                 os.remove(fn)
00063                 del(self.store[ID])
00064         except:
00065             log.msg()