home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / digsby_setup85.exe / lib / util / cacheable.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-11-24  |  10.3 KB  |  402 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from __future__ import with_statement
  5. __metaclass__ = type
  6. from introspect import base_classes
  7. import stdpaths
  8. import httplib2
  9. from logging import getLogger
  10. log = getLogger('cacheable')
  11. info = log.info
  12. from os.path import split as pathsplit, exists as pathexists
  13. import os
  14. import sys
  15. import traceback
  16. from zlib import compress, decompress
  17. import cPickle
  18. import simplejson
  19. import syck
  20.  
  21. try:
  22.     sentinel
  23. except NameError:
  24.     
  25.     class Sentinel(object):
  26.         
  27.         def __repr__(self):
  28.             return '<Sentinel (%r backup) %#x>' % (__file__, id(self))
  29.  
  30.  
  31.     sentinel = Sentinel()
  32.  
  33. _cacheattr = '__cached'
  34.  
  35. def save_cache_object(name, obj, user = False, json = False):
  36.     dumps = None if json else cPickle.dumps
  37.     croot = get_cache_root(user)
  38.     if not croot.isdir():
  39.         croot.makedirs()
  40.     
  41.     
  42.     try:
  43.         f = _[1]
  44.         f.write(compress(dumps(obj)))
  45.     finally:
  46.         pass
  47.  
  48.  
  49.  
  50. def load_cache_object(name, user = False, json = False):
  51.     p = get_cache_root(user) / name
  52.     if not p.isfile():
  53.         return None
  54.     loads = p.isfile() if json else cPickle.loads
  55.     
  56.     try:
  57.         f = _[1]
  58.         return loads(decompress(f.read()))
  59.     finally:
  60.         pass
  61.  
  62.  
  63. cache_formats = dict(json = (simplejson.dumps, simplejson.loads), pickle = (cPickle.dumps, simplejson.loads), yaml = (syck.dump, syck.load))
  64. cache_formats[None] = (((lambda x: x), (lambda x: x)),)
  65.  
  66. class DiskCache(object):
  67.     
  68.     def __init__(self, name, user = True, format = 'json', compression = 'zip', validator = None):
  69.         (self.dumps, self.loads) = cache_formats[format]
  70.         self.filename = get_cache_root(user) / name
  71.         self.format = format
  72.         self.compression = compression
  73.         self.validator = validator
  74.  
  75.     
  76.     def remove(self):
  77.         
  78.         try:
  79.             if self.exists():
  80.                 self.filename.remove()
  81.         except Exception:
  82.             traceback.print_exc()
  83.  
  84.  
  85.     
  86.     def exists(self):
  87.         
  88.         try:
  89.             return self.filename.isfile()
  90.         except Exception:
  91.             traceback.print_exc()
  92.             return False
  93.  
  94.  
  95.     
  96.     def safe_load(self, default_func = (lambda : pass)):
  97.         
  98.         try:
  99.             if self.exists():
  100.                 return self.load()
  101.         except Exception:
  102.             traceback.print_exc()
  103.  
  104.         return default_func()
  105.  
  106.     
  107.     def load(self):
  108.         
  109.         try:
  110.             f = _[1]
  111.             val = f.read()
  112.         finally:
  113.             pass
  114.  
  115.         
  116.         try:
  117.             val = val.decode('z')
  118.         except Exception:
  119.             open(self.filename, 'rb').__exit__
  120.             open(self.filename, 'rb').__exit__
  121.             open(self.filename, 'rb')
  122.             if self.compression is not None:
  123.                 val = val.decode(self.compression)
  124.             
  125.         except:
  126.             self.compression is not None
  127.  
  128.         obj = self.loads(val)
  129.         return obj
  130.  
  131.     
  132.     def save(self, obj):
  133.         
  134.         try:
  135.             val = self.dumps(obj)
  136.             if self.compression is not None:
  137.                 val = val.encode(self.compression)
  138.             
  139.             
  140.             try:
  141.                 f = _[1]
  142.                 f.write(val)
  143.             finally:
  144.                 pass
  145.  
  146.         except Exception:
  147.             traceback.print_exc()
  148.             return False
  149.  
  150.         return True
  151.  
  152.     
  153.     def __repr__(self):
  154.         return '<%s at %r, format=%s>' % (self.__class__.__name__, self.filename, self.format)
  155.  
  156.  
  157.  
  158. def get_cache_root(user = False):
  159.     root = stdpaths.userlocaldata / 'cache'
  160.     if user:
  161.         profile = profile
  162.         import common
  163.         if profile:
  164.             name = profile.username
  165.         else:
  166.             name = ''
  167.         root = root / (name + '_cache')
  168.     
  169.     return root
  170.  
  171.  
  172. def get_obj_cache_path(obj, user = False):
  173.     ocp = getattr(obj, 'cache_path', '')
  174.     if not ocp:
  175.         import warnings
  176.         warnings.warn('%r does not have a cache path, you really should give it one.' % obj)
  177.     
  178.     return get_cache_root(user) / ocp
  179.  
  180.  
  181. def clear_file_cache(obj, user = False):
  182.     return os.remove(get_obj_cache_path(obj, user = user))
  183.  
  184.  
  185. def load_file_cache(obj, user = False):
  186.     cache_path = get_obj_cache_path(obj, user)
  187.     if not pathexists(cache_path):
  188.         return None
  189.     
  190.     try:
  191.         f = _[1]
  192.         return f.read()
  193.     finally:
  194.         pass
  195.  
  196.  
  197.  
  198. def save_file_cache(obj, data, user = False):
  199.     if not getattr(obj, '_disk_cacheable', True):
  200.         return None
  201.     cache_path = get_obj_cache_path(obj, user)
  202.     cache_head = pathsplit(cache_path)[0]
  203.     if not pathexists(cache_head):
  204.         os.makedirs(cache_head)
  205.     
  206.     
  207.     try:
  208.         f = _[1]
  209.         f.write(data)
  210.     finally:
  211.         pass
  212.  
  213.  
  214.  
  215. class cproperty:
  216.     
  217.     def __init__(self, default = sentinel, box = None, unbox = None, user = False):
  218.         self.default = default
  219.         if box is not None:
  220.             self.box = box
  221.             self.unbox = unbox
  222.         else:
  223.             self.box = self.unbox = (lambda o: o)
  224.         self.usermode = user
  225.  
  226.     
  227.     def load_cache(self, obj):
  228.         data = load_file_cache(obj, self.usermode)
  229.         if hasattr(obj, 'cache_crypt'):
  230.             if data is not None:
  231.                 
  232.                 try:
  233.                     data = obj.cache_crypt[1](data)
  234.                 except Exception:
  235.                     e = None
  236.                     traceback.print_exc()
  237.                     print repr(data), repr(e)
  238.                 except:
  239.                     None<EXCEPTION MATCH>Exception
  240.                 
  241.  
  242.             None<EXCEPTION MATCH>Exception
  243.         
  244.         
  245.         try:
  246.             boxed = None if data is not None else { }
  247.         except Exception:
  248.             e = None
  249.             traceback.print_exc()
  250.             boxed = { }
  251.  
  252.         cache = { }
  253.         error = False
  254.         for k, v in boxed.iteritems():
  255.             
  256.             try:
  257.                 cache.update({
  258.                     k: self.cacheprop(obj, k).unbox(v) })
  259.             continue
  260.             except Exception:
  261.                 traceback.print_exc()
  262.                 error = True
  263.                 continue
  264.             
  265.  
  266.         
  267.         if error:
  268.             log.warning('error retreiving cache for %s', obj)
  269.         
  270.         setattr(obj, _cacheattr, cache)
  271.         return cache
  272.  
  273.     
  274.     def save_cache(self, obj):
  275.         cache = getattr(obj, _cacheattr)
  276.         boxed = (None, dict)((lambda .0: for k, v in .0:
  277. (k, self.cacheprop(obj, k).box(v)))(cache.iteritems()))
  278.         compressed = compress(cPickle.dumps(boxed))
  279.         if hasattr(obj, 'cache_crypt'):
  280.             compressed = obj.cache_crypt[0](compressed)
  281.         
  282.         save_file_cache(obj, compressed, self.usermode)
  283.  
  284.     
  285.     def __get__(self, obj, objtype):
  286.         cache = getattr(obj, _cacheattr, sentinel)
  287.         if cache is sentinel:
  288.             
  289.             try:
  290.                 cache = self.load_cache(obj)
  291.             except Exception:
  292.                 traceback.print_exc()
  293.                 msg = 'error when getting cached attribute %s of %r' % (self.name(objtype), obj)
  294.                 print >>sys.stderr, msg
  295.                 cache = { }
  296.             except:
  297.                 None<EXCEPTION MATCH>Exception
  298.             
  299.  
  300.         None<EXCEPTION MATCH>Exception
  301.         name = self.name(objtype)
  302.         
  303.         try:
  304.             val = cache[name]
  305.         except KeyError:
  306.             
  307.             try:
  308.                 val = self.default()
  309.             except (AttributeError, TypeError):
  310.                 val = self.default
  311.  
  312.             if val is not sentinel:
  313.                 cache[name] = val
  314.             
  315.         except:
  316.             val is not sentinel
  317.  
  318.         if val is sentinel:
  319.             raise AttributeError
  320.         val is sentinel
  321.         return val
  322.  
  323.     
  324.     def name(self, objtype):
  325.         
  326.         try:
  327.             return self._name
  328.         except:
  329.             bases = [
  330.                 objtype] + base_classes(objtype)
  331.             for clz in bases:
  332.                 for k, v in clz.__dict__.iteritems():
  333.                     if v is self:
  334.                         self._name = k
  335.                         return k
  336.                 
  337.             
  338.  
  339.         raise AssertionError, str(bases)
  340.  
  341.     
  342.     def cacheprop(cls, objtype, name):
  343.         objtype = objtype.__class__
  344.         
  345.         try:
  346.             return vars(objtype)[name]
  347.         except:
  348.             bases = base_classes(objtype)
  349.             for base in bases:
  350.                 
  351.                 try:
  352.                     return vars(base)[name]
  353.                 continue
  354.                 except KeyError:
  355.                     continue
  356.                 
  357.  
  358.             
  359.  
  360.         raise AssertionError, 'cannot find %s in %s' % (name, objtype)
  361.  
  362.     cacheprop = classmethod(cacheprop)
  363.     
  364.     def __set__(self, obj, value):
  365.         cache = getattr(obj, _cacheattr, sentinel)
  366.         if cache is sentinel:
  367.             
  368.             try:
  369.                 cache = self.load_cache(obj)
  370.             except Exception:
  371.                 e = None
  372.                 traceback.print_exc()
  373.                 print >>sys.stderr, 'error loading cache for %r while setting value %s' % (obj, self.name(obj.__class__))
  374.                 cache = { }
  375.             except:
  376.                 None<EXCEPTION MATCH>Exception
  377.             
  378.  
  379.         None<EXCEPTION MATCH>Exception
  380.         cache[self.name(obj.__class__)] = value
  381.         
  382.         try:
  383.             self.save_cache(obj)
  384.         except Exception:
  385.             e = None
  386.             traceback.print_exc()
  387.             print >>sys.stderr, 'error saving cache for %r while setting value %s' % (obj, self.name(obj.__class__))
  388.  
  389.  
  390.     
  391.     def __delete__(self, obj):
  392.         self.fdel(obj)
  393.  
  394.  
  395.  
  396. def urlcacheopen(url, *a, **k):
  397.     http = httplib2.Http(cache = unicode(get_cache_root() / 'webcache'))
  398.     (resp, content) = http.request(url, *a, **k)
  399.     log.debug('%s for %s', resp.status, url)
  400.     return (resp, content)
  401.  
  402.