/usr/share/pyshared/jsb/utils/lazydict.py is in jsonbot 0.84.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | # jsb/utils/lazydict.py
#
# thnx to maze
""" a lazydict allows dotted access to a dict .. dict.key. """
## jsb imports
from jsb.utils.locking import lockdec
from jsb.utils.exception import handle_exception
from jsb.utils.trace import whichmodule, where
from jsb.lib.errors import PropertyIgnored
from jsb.imports import getjson
json = getjson()
## basic imports
from xml.sax.saxutils import unescape
import copy
import logging
import types
import threading
import os
import re
import types
## locks
lock = threading.RLock()
locked = lockdec(lock)
## defines
defaultignore = ['aliases', 'userhosts', 'owner', '_comments', 'result', 'plugs', 'origevent', 'passwords', 'key', 'finished', 'inqueue', 'resqueue', 'outqueue', 'waitlist', 'comments', 'createdfrom', 'webchannels', 'tokens', 'token', 'cmndperms', 'gatekeeper', 'stanza', 'isremote', 'iscmnd', 'orig', 'bot', 'origtxt', 'body', 'subelements', 'args', 'rest', 'pass', 'password', 'fsock', 'sock', 'handlers', 'users', 'plugins']
minignore = ['aliases', '_comments', 'plugs', 'user', 'chan', 'password', 'key', 'passwords', 'threads', 'comments']
dontshow = ['cfg', 'filename', 'origname', 'origdir', 'cfile', 'dir', 'filename', 'modname', 'dbpasswd', 'dbname', 'dbuser', 'datadir' , 'origdir', 'dbhost']
cpy = copy.deepcopy
## checkignore function
def checkignore(name, ignore):
""" see whether a element attribute (name) should be ignored. """
name = unicode(name)
if name.startswith('_'): return True
for item in ignore:
if item == name:
return True
return False
## stripignore function
def stripignore(d):
for name in defaultignore:
try: del d[name]
except KeyError: pass
return d
#@locked
def dumpelement(element, prev={}, withtypes=False, full=False):
""" check each attribute of element whether it is dumpable. """
try: elem = cpy(element)
except Exception, ex: logging.error("can't copy %s" % str(ex)) ; return str(type(element))
if not elem: elem = element
try: new = LazyDict(prev)
except (TypeError, ValueError): new = LazyDict()
for name in elem:
if not full and checkignore(name, defaultignore): continue
elif checkignore(name, minignore): continue
try:
json.dumps(elem[name])
try: new[name] = stripignore(elem[name])
except: new[name] = elem[name]
except TypeError:
if type(elem[name]) not in jsontypes:
if withtypes: new[name] = str(type(elem[name]))
else:
logging.warn("lazydict - dumpelement - %s" % elem[name])
new[name] = dumpelement(elem[name], new, full)
return new
## LazyDict class
class LazyDict(dict):
""" lazy dict allows dotted access to a dict """
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
def __deepcopy__(self, a):
return LazyDict(self)
def __unicode__(self):
return str(self).encode("utf-8")
def __getattr__(self, attr, default=""):
""" get attribute. """
if not self.has_key(attr): return cpy(default)
return self[attr]
def __setattr__(self, attr, value):
""" set attribute. """
if not self.overload and self.has_key(attr) and type(self[attr]) in [types.FunctionType, types.MethodType]:
mod = whichmodule(2)
raise Exception("lazydict - cannot change a function of method: %s - called from %s" % (attr, mod))
self[attr] = value
def all(self):
result = {}
for key, val in self.iteritems():
if type(val) not in [types.MethodType,]: result[key] = val
return result
def render(self, template):
temp = open(template, 'r').read()
for key, value in self.iteritems():
try: temp = temp.replace("{{ %s }}" % key, value)
except: pass
return temp
def dostring(self):
""" return a string representation of the dict """
res = ""
cp = dict(self)
for item, value in cp.iteritems(): res += "%r=%r " % (item, value)
return res
def tojson(self, withtypes=False, full=False):
""" dump the lazydict object to json. """
try:
return json.dumps(dumpelement(self, withtypes, full))
except RuntimeError, ex: raise
def dump(self, withtypes=False):
""" just dunp the lazydict object. DON'T convert to json. """
try: return dumpelement(self, withtypes)
except RuntimeError, ex: handle_exception()
def fordisplay(self):
res = self.dump()
for i in dontshow:
try: del res[i]
except KeyError: pass
return res.tojson()
def load(self, input):
""" load from json string. """
try: temp = json.loads(input)
except ValueError:
handle_exception()
logging.error("lazydict - can't decode %s" % input)
return self
if type(temp) != dict:
logging.error("lazydict - %s is not a dict" % str(temp))
return self
self.update(temp)
return self
def snapshot(self):
pass
def merge(self, input):
pass
def save(self):
pass
jsontypes = [types.StringType, types.UnicodeType, types.DictType, types.ListType, types.IntType, LazyDict]
|