home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / digsby_setup.exe / lib / util / cacheable.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-02-26  |  11.0 KB  |  412 lines

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