Changeset 2988
- Timestamp:
- 01/06/08 01:25:31 (11 months ago)
- Files:
-
- boxdbplugin/0.11/boxdb/db_default.py (modified) (2 diffs)
- boxdbplugin/0.11/boxdb/htdocs (added)
- boxdbplugin/0.11/boxdb/_simplejson/decoder.py (modified) (2 diffs)
- boxdbplugin/0.11/boxdb/_simplejson/encoder.py (modified) (4 diffs)
- boxdbplugin/0.11/boxdb/_simplejson/__init__.py (modified) (5 diffs)
- boxdbplugin/0.11/boxdb/templates (added)
- boxdbplugin/0.11/boxdb/templates/boxdb_edit.html (added)
- boxdbplugin/0.11/boxdb/web_ui.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
boxdbplugin/0.11/boxdb/db_default.py
r2986 r2988 5 5 6 6 name = 'boxdb' 7 version = 27 version = 3 8 8 tables = [ 9 9 Table('boxdb', key=('name', 'key'))[ … … 12 12 Column('value'), # JSON encoded 13 13 ], 14 Table('boxdb_changes', key=( ))[14 Table('boxdb_changes', key=('document', 'time', 'key'))[ 15 15 Column('document'), 16 16 Column('time'), boxdbplugin/0.11/boxdb/_simplejson/decoder.py
r2987 r2988 195 195 196 196 class JSONDecoder(object): 197 """198 Simple JSON <http://json.org> decoder199 200 Performs the following translations in decoding:201 202 +---------------+-------------------+203 | JSON | Python |204 +===============+===================+205 | object | dict |206 +---------------+-------------------+207 | array | list |208 +---------------+-------------------+209 | string | unicode |210 +---------------+-------------------+211 | number (int) | int, long |212 +---------------+-------------------+213 | number (real) | float |214 +---------------+-------------------+215 | true | True |216 +---------------+-------------------+217 | false | False |218 +---------------+-------------------+219 | null | None |220 +---------------+-------------------+221 222 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as223 their corresponding ``float`` values, which is outside the JSON spec.224 """225 226 197 _scanner = Scanner(ANYTHING) 227 198 __all__ = ['__init__', 'decode', 'raw_decode'] 228 199 229 200 def __init__(self, encoding=None, object_hook=None): 230 """231 ``encoding`` determines the encoding used to interpret any ``str``232 objects decoded by this instance (utf-8 by default). It has no233 effect when decoding ``unicode`` objects.234 235 Note that currently only encodings that are a superset of ASCII work,236 strings of other encodings should be passed in as ``unicode``.237 238 ``object_hook``, if specified, will be called with the result239 of every JSON object decoded and its return value will be used in240 place of the given ``dict``. This can be used to provide custom241 deserializations (e.g. to support JSON-RPC class hinting).242 """243 201 self.encoding = encoding 244 202 self.object_hook = object_hook … … 256 214 257 215 def raw_decode(self, s, **kw): 258 """259 Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning260 with a JSON document) and return a 2-tuple of the Python261 representation and the index in ``s`` where the document ended.262 263 This can be used to decode a JSON document from a string that may264 have extraneous data at the end.265 """266 216 kw.setdefault('context', self) 267 217 try: boxdbplugin/0.11/boxdb/_simplejson/encoder.py
r2986 r2988 76 76 77 77 class JSONEncoder(object): 78 """79 Extensible JSON <http://json.org> encoder for Python data structures.80 81 Supports the following objects and types by default:82 83 +-------------------+---------------+84 | Python | JSON |85 +===================+===============+86 | dict | object |87 +-------------------+---------------+88 | list, tuple | array |89 +-------------------+---------------+90 | str, unicode | string |91 +-------------------+---------------+92 | int, long, float | number |93 +-------------------+---------------+94 | True | true |95 +-------------------+---------------+96 | False | false |97 +-------------------+---------------+98 | None | null |99 +-------------------+---------------+100 101 To extend this to recognize other objects, subclass and implement a102 ``.default()`` method with another method that returns a serializable103 object for ``o`` if possible, otherwise it should call the superclass104 implementation (to raise ``TypeError``).105 """106 78 __all__ = ['__init__', 'default', 'encode', 'iterencode'] 107 79 item_separator = ', ' … … 110 82 check_circular=True, allow_nan=True, sort_keys=False, 111 83 indent=None, separators=None, encoding='utf-8'): 112 """113 Constructor for JSONEncoder, with sensible defaults.114 115 If skipkeys is False, then it is a TypeError to attempt116 encoding of keys that are not str, int, long, float or None. If117 skipkeys is True, such items are simply skipped.118 119 If ensure_ascii is True, the output is guaranteed to be str120 objects with all incoming unicode characters escaped. If121 ensure_ascii is false, the output will be unicode object.122 123 If check_circular is True, then lists, dicts, and custom encoded124 objects will be checked for circular references during encoding to125 prevent an infinite recursion (which would cause an OverflowError).126 Otherwise, no such check takes place.127 128 If allow_nan is True, then NaN, Infinity, and -Infinity will be129 encoded as such. This behavior is not JSON specification compliant,130 but is consistent with most JavaScript based encoders and decoders.131 Otherwise, it will be a ValueError to encode such floats.132 133 If sort_keys is True, then the output of dictionaries will be134 sorted by key; this is useful for regression tests to ensure135 that JSON serializations can be compared on a day-to-day basis.136 137 If indent is a non-negative integer, then JSON array138 elements and object members will be pretty-printed with that139 indent level. An indent level of 0 will only insert newlines.140 None is the most compact representation.141 142 If specified, separators should be a (item_separator, key_separator)143 tuple. The default is (', ', ': '). To get the most compact JSON144 representation you should specify (',', ':') to eliminate whitespace.145 146 If encoding is not None, then all input strings will be147 transformed into unicode using that encoding prior to JSON-encoding.148 The default is UTF-8.149 """150 151 84 self.skipkeys = skipkeys 152 85 self.ensure_ascii = ensure_ascii … … 310 243 311 244 def default(self, o): 312 """313 Implement this method in a subclass such that it returns314 a serializable object for ``o``, or calls the base implementation315 (to raise a ``TypeError``).316 317 For example, to support arbitrary iterators, you could318 implement default like this::319 320 def default(self, o):321 try:322 iterable = iter(o)323 except TypeError:324 pass325 else:326 return list(iterable)327 return JSONEncoder.default(self, o)328 """329 245 raise TypeError("%r is not JSON serializable" % (o,)) 330 246 331 247 def encode(self, o): 332 """333 Return a JSON string representation of a Python data structure.334 335 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})336 '{"foo":["bar", "baz"]}'337 """338 248 # This is for extremely simple cases and benchmarks... 339 249 if isinstance(o, basestring): … … 351 261 352 262 def iterencode(self, o): 353 """354 Encode the given object and yield each string355 representation as available.356 357 For example::358 359 for chunk in JSONEncoder().iterencode(bigobject):360 mysocket.write(chunk)361 """362 263 if self.check_circular: 363 264 markers = {} boxdbplugin/0.11/boxdb/_simplejson/__init__.py
r2986 r2988 1 r"""2 A simple, fast, extensible JSON encoder and decoder3 4 JSON (JavaScript Object Notation) <http://json.org> is a subset of5 JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data6 interchange format.7 8 simplejson exposes an API familiar to uses of the standard library9 marshal and pickle modules.10 11 Encoding basic Python object hierarchies::12 13 >>> import simplejson14 >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])15 '["foo", {"bar": ["baz", null, 1.0, 2]}]'16 >>> print simplejson.dumps("\"foo\bar")17 "\"foo\bar"18 >>> print simplejson.dumps(u'\u1234')19 "\u1234"20 >>> print simplejson.dumps('\\')21 "\\"22 >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)23 {"a": 0, "b": 0, "c": 0}24 >>> from StringIO import StringIO25 >>> io = StringIO()26 >>> simplejson.dump(['streaming API'], io)27 >>> io.getvalue()28 '["streaming API"]'29 30 Compact encoding::31 32 >>> import simplejson33 >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))34 '[1,2,3,{"4":5,"6":7}]'35 36 Pretty printing::37 38 >>> import simplejson39 >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)40 {41 "4": 5,42 "6": 743 }44 45 Decoding JSON::46 47 >>> import simplejson48 >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')49 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]50 >>> simplejson.loads('"\\"foo\\bar"')51 u'"foo\x08ar'52 >>> from StringIO import StringIO53 >>> io = StringIO('["streaming API"]')54 >>> simplejson.load(io)55 [u'streaming API']56 57 Specializing JSON object decoding::58 59 >>> import simplejson60 >>> def as_complex(dct):61 ... if '__complex__' in dct:62 ... return complex(dct['real'], dct['imag'])63 ... return dct64 ...65 >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',66 ... object_hook=as_complex)67 (1+2j)68 69 Extending JSONEncoder::70 71 >>> import simplejson72 >>> class ComplexEncoder(simplejson.JSONEncoder):73 ... def default(self, obj):74 ... if isinstance(obj, complex):75 ... return [obj.real, obj.imag]76 ... return simplejson.JSONEncoder.default(self, obj)77 ...78 >>> dumps(2 + 1j, cls=ComplexEncoder)79 '[2.0, 1.0]'80 >>> ComplexEncoder().encode(2 + 1j)81 '[2.0, 1.0]'82 >>> list(ComplexEncoder().iterencode(2 + 1j))83 ['[', '2.0', ', ', '1.0', ']']84 85 86 Note that the JSON produced by this module's default settings87 is a subset of YAML, so it may be used as a serializer for that as well.88 """89 1 __version__ = '1.7' 90 2 __all__ = [ … … 109 21 allow_nan=True, cls=None, indent=None, encoding='utf-8', 110 22 **kw): 111 """112 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a113 ``.write()``-supporting file-like object).114 115 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types116 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)117 will be skipped instead of raising a ``TypeError``.118 119 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``120 may be ``unicode`` instances, subject to normal Python ``str`` to121 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly122 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely123 to cause an error.124 125 If ``check_circular`` is ``False``, then the circular reference check126 for container types will be skipped and a circular reference will127 result in an ``OverflowError`` (or worse).128 129 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to130 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)131 in strict compliance of the JSON specification, instead of using the132 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).133 134 If ``indent`` is a non-negative integer, then JSON array elements and object135 members will be pretty-printed with that indent level. An indent level136 of 0 will only insert newlines. ``None`` is the most compact representation.137 138 ``encoding`` is the character encoding for str instances, default is UTF-8.139 140 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the141 ``.default()`` method to serialize additional types), specify it with142 the ``cls`` kwarg.143 """144 23 # cached encoder 145 24 if (skipkeys is False and ensure_ascii is True and … … 163 42 allow_nan=True, cls=None, indent=None, separators=None, 164 43 encoding='utf-8', **kw): 165 """166 Serialize ``obj`` to a JSON formatted ``str``.167 168 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types169 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)170 will be skipped instead of raising a ``TypeError``.171 172 If ``ensure_ascii`` is ``False``, then the return value will be a173 ``unicode`` instance subject to normal Python ``str`` to ``unicode``174 coercion rules instead of being escaped to an ASCII ``str``.175 176 If ``check_circular`` is ``False``, then the circular reference check177 for container types will be skipped and a circular reference will178 result in an ``OverflowError`` (or worse).179 180 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to181 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in182 strict compliance of the JSON specification, instead of using the183 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).184 185 If ``indent`` is a non-negative integer, then JSON array elements and186 object members will be pretty-printed with that indent level. An indent187 level of 0 will only insert newlines. ``None`` is the most compact188 representation.189 190 If ``separators`` is an ``(item_separator, dict_separator)`` tuple191 then it will be used instead of the default ``(', ', ': ')`` separators.192 ``(',', ':')`` is the most compact JSON representation.193 194 ``encoding`` is the character encoding for str instances, default is UTF-8.195 196 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the197 ``.default()`` method to serialize additional types), specify it with198 the ``cls`` kwarg.199 """200 44 # cached encoder 201 45 if (skipkeys is False and ensure_ascii is True and … … 215 59 216 60 def load(fp, encoding=None, cls=None, object_hook=None, **kw): 217 """218 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing219 a JSON document) to a Python object.220 221 If the contents of ``fp`` is encoded with an ASCII based encoding other222 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must223 be specified. Encodings that are not ASCII based (such as UCS-2) are224 not allowed, and should be wrapped with225 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``226 object and passed to ``loads()``227 228 ``object_hook`` is an optional function that will be called with the229 result of any object literal decode (a ``dict``). The return value of230 ``object_hook`` will be used instead of the ``dict``. This feature231 can be used to implement custom decoders (e.g. JSON-RPC class hinting).232 233 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``234 kwarg.235 """236 61 return loads(fp.read(), 237 62 encoding=encoding, cls=cls, object_hook=object_hook, **kw) 238 63 239 64 def loads(s, encoding=None, cls=None, object_hook=None, **kw): 240 """241 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON242 document) to a Python object.243 244 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding245 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name246 must be specified. Encodings that are not ASCII based (such as UCS-2)247 are not allowed and should be decoded to ``unicode`` first.248 249 ``object_hook`` is an optional function that will be called with the250 result of any object literal decode (a ``dict``). The return value of251 ``object_hook`` will be used instead of the ``dict``. This feature252 can be used to implement custom decoders (e.g. JSON-RPC class hinting).253 254 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``255 kwarg.256 """257 65 if cls is None and encoding is None and object_hook is None and not kw: 258 66 return _default_decoder.decode(s) … … 263 71 return cls(encoding=encoding, **kw).decode(s) 264 72 265 def read(s):266 """267 json-py API compatibility hook. Use loads(s) instead.268 """269 import warnings270 warnings.warn("simplejson.loads(s) should be used instead of read(s)",271 DeprecationWarning)272 return loads(s)273 73 274 def write(obj):275 """276 json-py API compatibility hook. Use dumps(s) instead.277 """278 import warnings279 warnings.warn("simplejson.dumps(s) should be used instead of write(s)",280 DeprecationWarning)281 return dumps(obj)282 283 boxdbplugin/0.11/boxdb/web_ui.py
r2986 r2988 2 2 # Copyright (c) 2007 Noah Kantrowitz. All rights reserved. 3 3 4 from genshi.builder import tag 5 4 6 from trac.core import * 7 from trac.web.api import IRequestHandler 8 from trac.web.chrome import INavigationContributor, ITemplateProvider 9 from trac.perm import IPermissionRequestor 5 10 6 11 class BoxDBModule(Component): 7 """Simple d atabase system to use from Trac."""12 """Simple document database system to use from Trac.""" 8 13 9 implements() 14 implements(IRequestHandler, INavigationContributor, IPermissionRequestor, 15 ITemplateProvider) 16 17 # IRequestHandler methods 18 def match_request(self, req): 19 return req.path_info.startswith('/document') 10 20 11 21 def process_request(self, req): 22 data = {} 23 path_info = req.path_info[10:] 24 25 return 'boxdb_edit.html', data, None 26 27 # INavigationContributor methods 28 def get_active_navigation_item(self, req): 29 return 'documents' 30 31 def get_navigation_items(self, req): 32 if req.perm.has_permission('DOCUMENT_VIEW'): 33 yield 'mainnav', 'documents', tag.a('Documents', href=req.href.document()) 34 35 # IPermissionRequestor methods 36 def get_permission_actions(self): 37 yield 'DOCUMENT_VIEW' 38 39 # ITemplateProvider methods 40 def get_htdocs_dirs(self): 41 from pkg_resources import resource_filename 42 return [('boxdb', resource_filename(__name__, 'htdocs'))] 43 44 def get_templates_dirs(self): 45 from pkg_resources import resource_filename 46 return [resource_filename(__name__, 'templates')]
