Changeset 8215 for django/branches/gis/django/utils
- Timestamp:
- 08/05/08 12:15:33 (4 months ago)
- Files:
-
- django/branches/gis (modified) (1 prop)
- django/branches/gis/django/utils/cache.py (modified) (4 diffs)
- django/branches/gis/django/utils/dateformat.py (modified) (1 diff)
- django/branches/gis/django/utils/encoding.py (modified) (1 diff)
- django/branches/gis/django/utils/functional.py (modified) (1 diff)
- django/branches/gis/django/utils/hashcompat.py (copied) (copied from django/trunk/django/utils/hashcompat.py)
- django/branches/gis/django/utils/html.py (modified) (2 diffs)
- django/branches/gis/django/utils/http.py (modified) (1 diff)
- django/branches/gis/django/utils/maxlength.py (deleted)
- django/branches/gis/django/utils/simplejson/decoder.py (modified) (16 diffs)
- django/branches/gis/django/utils/simplejson/encoder.py (modified) (11 diffs)
- django/branches/gis/django/utils/simplejson/__init__.py (modified) (15 diffs)
- django/branches/gis/django/utils/simplejson/jsonfilter.py (deleted)
- django/branches/gis/django/utils/simplejson/LICENSE.txt (modified) (1 diff)
- django/branches/gis/django/utils/simplejson/scanner.py (modified) (3 diffs)
- django/branches/gis/django/utils/simplejson/tool.py (copied) (copied from django/trunk/django/utils/simplejson/tool.py)
- django/branches/gis/django/utils/thread_support.py (copied) (copied from django/trunk/django/utils/thread_support.py)
- django/branches/gis/django/utils/translation/trans_real.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/branches/gis
- Property svnmerge-integrated changed from /django/trunk:1-7978 to /django/trunk:1-8214
django/branches/gis/django/utils/cache.py
r7768 r8215 18 18 """ 19 19 20 import md521 20 import re 22 21 import time … … 30 29 from django.utils.encoding import smart_str, iri_to_uri 31 30 from django.utils.http import http_date 31 from django.utils.hashcompat import md5_constructor 32 32 33 33 cc_delim_re = re.compile(r'\s*,\s*') … … 105 105 cache_timeout = 0 # Can't have max-age negative 106 106 if not response.has_header('ETag'): 107 response['ETag'] = '"%s"' % md5 .new(response.content).hexdigest()107 response['ETag'] = '"%s"' % md5_constructor(response.content).hexdigest() 108 108 if not response.has_header('Last-Modified'): 109 109 response['Last-Modified'] = http_date() … … 139 139 def _generate_cache_key(request, headerlist, key_prefix): 140 140 """Returns a cache key from the headers given in the header list.""" 141 ctx = md5 .new()141 ctx = md5_constructor() 142 142 for header in headerlist: 143 143 value = request.META.get(header, None) django/branches/gis/django/utils/dateformat.py
r6672 r8215 14 14 from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR 15 15 from django.utils.tzinfo import LocalTimezone 16 from django.utils.translation import string_concat,ugettext as _16 from django.utils.translation import ugettext as _ 17 17 from django.utils.encoding import force_unicode 18 18 from calendar import isleap, monthrange django/branches/gis/django/utils/encoding.py
r7103 r8215 2 2 import urllib 3 3 import datetime 4 5 4 from django.utils.functional import Promise 6 from django.utils.safestring import SafeData, mark_safe7 5 8 6 class DjangoUnicodeDecodeError(UnicodeDecodeError): django/branches/gis/django/utils/functional.py
r7176 r8215 149 149 """ 150 150 class __proxy__(Promise): 151 # This inner class encapsulates the code that should be evaluated 152 # lazily. On calling of one of the magic methods it will force 153 # the evaluation and store the result. Afterwards, the result 154 # is delivered directly. So the result is memoized. 151 """ 152 Encapsulate a function call and act as a proxy for methods that are 153 called on the result of that function. The function is not evaluated 154 until one of the methods on the result is called. 155 """ 156 __dispatch = None 157 155 158 def __init__(self, args, kw): 156 159 self.__func = func 157 160 self.__args = args 158 161 self.__kw = kw 159 self.__dispatch = {} 162 if self.__dispatch is None: 163 self.__prepare_class__() 164 165 def __prepare_class__(cls): 166 cls.__dispatch = {} 160 167 for resultclass in resultclasses: 161 self.__dispatch[resultclass] = {}168 cls.__dispatch[resultclass] = {} 162 169 for (k, v) in resultclass.__dict__.items(): 163 setattr(self, k, self.__promise__(resultclass, k, v)) 164 self._delegate_str = str in resultclasses 165 self._delegate_unicode = unicode in resultclasses 166 assert not (self._delegate_str and self._delegate_unicode), "Cannot call lazy() with both str and unicode return types." 167 if self._delegate_unicode: 168 # Each call to lazy() makes a new __proxy__ object, so this 169 # doesn't interfere with any other lazy() results. 170 __proxy__.__unicode__ = __proxy__.__unicode_cast 171 elif self._delegate_str: 172 __proxy__.__str__ = __proxy__.__str_cast 173 174 def __promise__(self, klass, funcname, func): 170 if hasattr(cls, k): 171 continue 172 setattr(cls, k, cls.__promise__(resultclass, k, v)) 173 cls._delegate_str = str in resultclasses 174 cls._delegate_unicode = unicode in resultclasses 175 assert not (cls._delegate_str and cls._delegate_unicode), "Cannot call lazy() with both str and unicode return types." 176 if cls._delegate_unicode: 177 cls.__unicode__ = cls.__unicode_cast 178 elif cls._delegate_str: 179 cls.__str__ = cls.__str_cast 180 __prepare_class__ = classmethod(__prepare_class__) 181 182 def __promise__(cls, klass, funcname, func): 175 183 # Builds a wrapper around some magic method and registers that magic 176 184 # method for the given type and method name. 177 def __wrapper__( *args, **kw):185 def __wrapper__(self, *args, **kw): 178 186 # Automatically triggers the evaluation of a lazy value and 179 187 # applies the given magic method of the result type. 180 188 res = self.__func(*self.__args, **self.__kw) 181 return self.__dispatch[type(res)][funcname](res, *args, **kw) 182 183 if klass not in self.__dispatch: 184 self.__dispatch[klass] = {} 185 self.__dispatch[klass][funcname] = func 189 for t in type(res).mro(): 190 if t in self.__dispatch: 191 return self.__dispatch[t][funcname](res, *args, **kw) 192 raise TypeError("Lazy object returned unexpected type.") 193 194 if klass not in cls.__dispatch: 195 cls.__dispatch[klass] = {} 196 cls.__dispatch[klass][funcname] = func 186 197 return __wrapper__ 198 __promise__ = classmethod(__promise__) 187 199 188 200 def __unicode_cast(self): django/branches/gis/django/utils/html.py
r7768 r8215 95 95 nofollow_attr = nofollow and ' rel="nofollow"' or '' 96 96 for i, word in enumerate(words): 97 match = punctuation_re.match(word) 97 match = None 98 if '.' in word or '@' in word or ':' in word: 99 match = punctuation_re.match(word) 98 100 if match: 99 101 lead, middle, trail = match.groups() … … 103 105 url = urlquote(middle, safe='/&=:;#?+*') 104 106 elif middle.startswith('www.') or ('@' not in middle and \ 105 len(middle) > 0and middle[0] in string.ascii_letters + string.digits and \107 middle and middle[0] in string.ascii_letters + string.digits and \ 106 108 (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))): 107 109 url = urlquote('http://%s' % middle, safe='/&=:;#?+*') django/branches/gis/django/utils/http.py
r6672 r8215 66 66 rfcdate = formatdate(epoch_seconds) 67 67 return '%s GMT' % rfcdate[:25] 68 69 # Base 36 functions: useful for generating compact URLs 70 71 def base36_to_int(s): 72 """ 73 Convertd a base 36 string to an integer 74 """ 75 return int(s, 36) 76 77 def int_to_base36(i): 78 """ 79 Converts an integer to a base36 string 80 """ 81 digits = "0123456789abcdefghijklmnopqrstuvwxyz" 82 factor = 0 83 # Find starting factor 84 while True: 85 factor += 1 86 if i < 36 ** factor: 87 factor -= 1 88 break 89 base36 = [] 90 # Construct base36 representation 91 while factor >= 0: 92 j = 36 ** factor 93 base36.append(digits[i / j]) 94 i = i % j 95 factor -= 1 96 return ''.join(base36) django/branches/gis/django/utils/simplejson/decoder.py
r4454 r8215 3 3 """ 4 4 import re 5 import sys 5 6 6 7 from django.utils.simplejson.scanner import Scanner, pattern 8 try: 9 from django.utils.simplejson._speedups import scanstring as c_scanstring 10 except ImportError: 11 pass 7 12 8 13 FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL … … 19 24 NaN, PosInf, NegInf = _floatconstants() 20 25 26 21 27 def linecol(doc, pos): 22 28 lineno = doc.count('\n', 0, pos) + 1 … … 27 33 return lineno, colno 28 34 35 29 36 def errmsg(msg, doc, pos, end=None): 30 37 lineno, colno = linecol(doc, pos) … … 34 41 return '%s: line %d column %d - line %d column %d (char %d - %d)' % ( 35 42 msg, lineno, colno, endlineno, endcolno, pos, end) 43 36 44 37 45 _CONSTANTS = { … … 45 53 46 54 def JSONConstant(match, context, c=_CONSTANTS): 47 return c[match.group(0)], None 55 s = match.group(0) 56 fn = getattr(context, 'parse_constant', None) 57 if fn is None: 58 rval = c[s] 59 else: 60 rval = fn(s) 61 return rval, None 48 62 pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant) 63 49 64 50 65 def JSONNumber(match, context): … … 52 67 integer, frac, exp = match.groups() 53 68 if frac or exp: 54 res = float(integer + (frac or '') + (exp or '')) 69 fn = getattr(context, 'parse_float', None) or float 70 res = fn(integer + (frac or '') + (exp or '')) 55 71 else: 56 res = int(integer) 72 fn = getattr(context, 'parse_int', None) or int 73 res = fn(integer) 57 74 return res, None 58 75 pattern(r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?')(JSONNumber) 59 76 60 STRINGCHUNK = re.compile(r'(.*?)(["\\])', FLAGS) 77 78 STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS) 61 79 BACKSLASH = { 62 80 '"': u'"', '\\': u'\\', '/': u'/', … … 66 84 DEFAULT_ENCODING = "utf-8" 67 85 68 def scanstring(s, end, encoding=None, _b=BACKSLASH, _m=STRINGCHUNK.match):86 def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match): 69 87 if encoding is None: 70 88 encoding = DEFAULT_ENCODING … … 85 103 if terminator == '"': 86 104 break 105 elif terminator != '\\': 106 if strict: 107 raise ValueError(errmsg("Invalid control character %r at", s, end)) 108 else: 109 _append(terminator) 110 continue 87 111 try: 88 112 esc = s[end] … … 99 123 else: 100 124 esc = s[end + 1:end + 5] 125 next_end = end + 5 126 msg = "Invalid \\uXXXX escape" 101 127 try: 102 m = unichr(int(esc, 16)) 103 if len(esc) != 4 or not esc.isalnum(): 128 if len(esc) != 4: 104 129 raise ValueError 130 uni = int(esc, 16) 131 if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535: 132 msg = "Invalid \\uXXXX\\uXXXX surrogate pair" 133 if not s[end + 5:end + 7] == '\\u': 134 raise ValueError 135 esc2 = s[end + 7:end + 11] 136 if len(esc2) != 4: 137 raise ValueError 138 uni2 = int(esc2, 16) 139 uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00)) 140 next_end += 6 141 m = unichr(uni) 105 142 except ValueError: 106 raise ValueError(errmsg( "Invalid \\uXXXX escape", s, end))107 end += 5143 raise ValueError(errmsg(msg, s, end)) 144 end = next_end 108 145 _append(m) 109 146 return u''.join(chunks), end 110 147 148 149 # Use speedup 150 try: 151 scanstring = c_scanstring 152 except NameError: 153 scanstring = py_scanstring 154 111 155 def JSONString(match, context): 112 156 encoding = getattr(context, 'encoding', None) 113 return scanstring(match.string, match.end(), encoding) 157 strict = getattr(context, 'strict', True) 158 return scanstring(match.string, match.end(), encoding, strict) 114 159 pattern(r'"')(JSONString) 160 115 161 116 162 WHITESPACE = re.compile(r'\s*', FLAGS) … … 121 167 end = _w(s, match.end()).end() 122 168 nextchar = s[end:end + 1] 123 # trivial empty object169 # Trivial empty object 124 170 if nextchar == '}': 125 171 return pairs, end + 1 … … 128 174 end += 1 129 175 encoding = getattr(context, 'encoding', None) 176 strict = getattr(context, 'strict', True) 130 177 iterscan = JSONScanner.iterscan 131 178 while True: 132 key, end = scanstring(s, end, encoding )179 key, end = scanstring(s, end, encoding, strict) 133 180 end = _w(s, end).end() 134 181 if s[end:end + 1] != ':': … … 157 204 return pairs, end 158 205 pattern(r'{')(JSONObject) 159 206 207 160 208 def JSONArray(match, context, _w=WHITESPACE.match): 161 209 values = [] 162 210 s = match.string 163 211 end = _w(s, match.end()).end() 164 # look-ahead for trivial empty array212 # Look-ahead for trivial empty array 165 213 nextchar = s[end:end + 1] 166 214 if nextchar == ']': … … 183 231 return values, end 184 232 pattern(r'\[')(JSONArray) 185 233 234 186 235 ANYTHING = [ 187 236 JSONObject, … … 194 243 JSONScanner = Scanner(ANYTHING) 195 244 245 196 246 class JSONDecoder(object): 197 247 """ 198 248 Simple JSON <http://json.org> decoder 199 249 200 Performs the following translations in decoding :250 Performs the following translations in decoding by default: 201 251 202 252 +---------------+-------------------+ … … 227 277 __all__ = ['__init__', 'decode', 'raw_decode'] 228 278 229 def __init__(self, encoding=None, object_hook=None): 279 def __init__(self, encoding=None, object_hook=None, parse_float=None, 280 parse_int=None, parse_constant=None, strict=True): 230 281 """ 231 282 ``encoding`` determines the encoding used to interpret any ``str`` … … 240 291 place of the given ``dict``. This can be used to provide custom 241 292 deserializations (e.g. to support JSON-RPC class hinting). 293 294 ``parse_float``, if specified, will be called with the string 295 of every JSON float to be decoded. By default this is equivalent to 296 float(num_str). This can be used to use another datatype or parser 297 for JSON floats (e.g. decimal.Decimal). 298 299 ``parse_int``, if specified, will be called with the string 300 of every JSON int to be decoded. By default this is equivalent to 301 int(num_str). This can be used to use another datatype or parser 302 for JSON integers (e.g. float). 303 304 ``parse_constant``, if specified, will be called with one of the 305 following strings: -Infinity, Infinity, NaN, null, true, false. 306 This can be used to raise an exception if invalid JSON numbers 307 are encountered. 242 308 """ 243 309 self.encoding = encoding 244 310 self.object_hook = object_hook 311 self.parse_float = parse_float 312 self.parse_int = parse_int 313 self.parse_constant = parse_constant 314 self.strict = strict 245 315 246 316 def decode(self, s, _w=WHITESPACE.match): django/branches/gis/django/utils/simplejson/encoder.py
r4454 r8215 4 4 import re 5 5 6 ESCAPE = re.compile(r'[\x00-\x19\\"\b\f\n\r\t]') 7 ESCAPE_ASCII = re.compile(r'([\\"/]|[^\ -~])') 6 try: 7 from django.utils.simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii 8 except ImportError: 9 pass 10 11 ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') 12 ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])') 13 HAS_UTF8 = re.compile(r'[\x80-\xff]') 8 14 ESCAPE_DCT = { 9 # escape all forward slashes to prevent </script> attack10 '/': '\\/',11 15 '\\': '\\\\', 12 16 '"': '\\"', … … 20 24 ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) 21 25 22 # assume this produces an infinity on all machines (probably not guaranteed)26 # Assume this produces an infinity on all machines (probably not guaranteed) 23 27 INFINITY = float('1e66666') 28 FLOAT_REPR = repr 24 29 25 30 def floatstr(o, allow_nan=True): … … 34 39 text = '-Infinity' 35 40 else: 36 return str(o)41 return FLOAT_REPR(o) 37 42 38 43 if not allow_nan: … … 51 56 return '"' + ESCAPE.sub(replace, s) + '"' 52 57 53 def encode_basestring_ascii(s): 58 59 def py_encode_basestring_ascii(s): 60 if isinstance(s, str) and HAS_UTF8.search(s) is not None: 61 s = s.decode('utf-8') 54 62 def replace(match): 55 63 s = match.group(0) … … 57 65 return ESCAPE_DCT[s] 58 66 except KeyError: 59 return '\\u%04x' % (ord(s),) 67 n = ord(s) 68 if n < 0x10000: 69 return '\\u%04x' % (n,) 70 else: 71 # surrogate pair 72 n -= 0x10000 73 s1 = 0xd800 | ((n >> 10) & 0x3ff) 74 s2 = 0xdc00 | (n & 0x3ff) 75 return '\\u%04x\\u%04x' % (s1, s2) 60 76 return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"' 61 77 78 79 try: 80 encode_basestring_ascii = c_encode_basestring_ascii 81 except NameError: 82 encode_basestring_ascii = py_encode_basestring_ascii 83 62 84 63 85 class JSONEncoder(object): … … 95 117 def __init__(self, skipkeys=False, ensure_ascii=True, 96 118 check_circular=True, allow_nan=True, sort_keys=False, 97 indent=None, separators=None ):119 indent=None, separators=None, encoding='utf-8', default=None): 98 120 """ 99 121 Constructor for JSONEncoder, with sensible defaults. … … 127 149 128 150 If specified, separators should be a (item_separator, key_separator) 129 tuple. The default is (', ', ': ').To get the most compact JSON151 tuple. The default is (', ', ': '). To get the most compact JSON 130 152 representation you should specify (',', ':') to eliminate whitespace. 153 154 If specified, default is a function that gets called for objects 155 that can't otherwise be serialized. It should return a JSON encodable 156 version of the object or raise a ``TypeError``. 157 158 If encoding is not None, then all input strings will be 159 transformed into unicode using that encoding prior to JSON-encoding. 160 The default is UTF-8. 131 161 """ 132 162 … … 140 170 if separators is not None: 141 171 self.item_separator, self.key_separator = separators 172 if default is not None: 173 self.default = default 174 self.encoding = encoding 142 175 143 176 def _newline_indent(self): … … 208 241 else: 209 242 items = dct.iteritems() 243 _encoding = self.encoding 244 _do_decode = (_encoding is not None 245 and not (_encoding == 'utf-8')) 210 246 for key, value in items: 211 if isinstance(key, basestring): 247 if isinstance(key, str): 248 if _do_decode: 249 key = key.decode(_encoding) 250 elif isinstance(key, basestring): 212 251 pass 213 252 # JavaScript is weakly typed for these, so it makes sense to … … 248 287 else: 249 288 encoder = encode_basestring 289 _encoding = self.encoding 290 if (_encoding is not None and isinstance(o, str) 291 and not (_encoding == 'utf-8')): 292 o = o.decode(_encoding) 250 293 yield encoder(o) 251 294 elif o is None: … … 305 348 306 349 >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) 307 '{"foo":["bar", "baz"]}' 308 """ 309 # This doesn't pass the iterator directly to ''.join() because it 310 # sucks at reporting exceptions. It's going to do this internally 311 # anyway because it uses PySequence_Fast or similar. 350 '{"foo": ["bar", "baz"]}' 351 """ 352 # This is for extremely simple cases and benchmarks. 353 if isinstance(o, basestring): 354 if isinstance(o, str): 355 _encoding = self.encoding 356 if (_encoding is not None 357 and not (_encoding == 'utf-8')): 358 o = o.decode(_encoding) 359 if self.ensure_ascii: 360 return encode_basestring_ascii(o) 361 else: 362 return encode_basestring(o) 363 # This doesn't pass the iterator directly to ''.join() because the 364 # exceptions aren't as detailed. The list call should be roughly 365 # equivalent to the PySequence_Fast that ''.join() would do. 312 366 chunks = list(self.iterencode(o)) 313 367 return ''.join(chunks) django/branches/gis/django/utils/simplejson/__init__.py
r4454 r8215 66 66 ... object_hook=as_complex) 67 67 (1+2j) 68 >>> import decimal 69 >>> simplejson.loads('1.1', parse_float=decimal.Decimal) 70 Decimal("1.1") 68 71 69 72 Extending JSONEncoder:: … … 84 87 85 88 89 Using simplejson from the shell to validate and 90 pretty-print:: 91 92 $ echo '{"json":"obj"}' | python -msimplejson.tool 93 { 94 "json": "obj" 95 } 96 $ echo '{ 1.2:3.4}' | python -msimplejson.tool 97 Expecting property name: line 1 column 2 (char 2) 98 86 99 Note that the JSON produced by this module's default settings 87 100 is a subset of YAML, so it may be used as a serializer for that as well. 88 101 """ 89 __version__ = '1. 5'102 __version__ = '1.9.2' 90 103 __all__ = [ 91 104 'dump', 'dumps', 'load', 'loads', … … 93 106 ] 94 107 95 from django.utils.simplejson.decoder import JSONDecoder 96 from django.utils.simplejson.encoder import JSONEncoder 108 if __name__ == '__main__': 109 import warnings 110 warnings.warn('python -msimplejson is deprecated, use python -msiplejson.tool', DeprecationWarning) 111 from django.utils.simplejson.decoder import JSONDecoder 112 from django.utils.simplejson.encoder import JSONEncoder 113 else: 114 from decoder import JSONDecoder 115 from encoder import JSONEncoder 116 117 _default_encoder = JSONEncoder( 118 skipkeys=False, 119 ensure_ascii=True, 120 check_circular=True, 121 allow_nan=True, 122 indent=None, 123 separators=None, 124 encoding='utf-8', 125 default=None, 126 ) 97 127 98 128 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, 99 allow_nan=True, cls=None, indent=None, **kw): 129 allow_nan=True, cls=None, indent=None, separators=None, 130 encoding='utf-8', default=None, **kw): 100 131 """ 101 132 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a … … 108 139 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` 109 140 may be ``unicode`` instances, subject to normal Python ``str`` to 110 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly141 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly 111 142 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely 112 143 to cause an error. … … 122 153 123 154 If ``indent`` is a non-negative integer, then JSON array elements and object 124 members will be pretty-printed with that indent level. An indent level 125 of 0 will only insert newlines. ``None`` is the most compact representation. 155 members will be pretty-printed with that indent level. An indent level 156 of 0 will only insert newlines. ``None`` is the most compact representation. 157 158 If ``separators`` is an ``(item_separator, dict_separator)`` tuple 159 then it will be used instead of the default ``(', ', ': ')`` separators. 160 ``(',', ':')`` is the most compact JSON representation. 161 162 ``encoding`` is the character encoding for str instances, default is UTF-8. 163 164 ``default(obj)`` is a function that should return a serializable version 165 of obj or raise TypeError. The default simply raises TypeError. 126 166 127 167 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the … … 129 169 the ``cls`` kwarg. 130 170 """ 131 if cls is None: 132 cls = JSONEncoder 133 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, 134 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 135 **kw).iterencode(obj) 171 # cached encoder 172 if (skipkeys is False and ensure_ascii is True and 173 check_circular is True and allow_nan is True and 174 cls is None and indent is None and separators is None and 175 encoding == 'utf-8' and default is None and not kw): 176 iterable = _default_encoder.iterencode(obj) 177 else: 178 if cls is None: 179 cls = JSONEncoder 180 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, 181 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 182 separators=separators, encoding=encoding, 183 default=default, **kw).iterencode(obj) 136 184 # could accelerate with writelines in some versions of Python, at 137 185 # a debuggability cost … … 139 187 fp.write(chunk) 140 188 189 141 190 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, 142 allow_nan=True, cls=None, indent=None, separators=None, **kw): 191 allow_nan=True, cls=None, indent=None, separators=None, 192 encoding='utf-8', default=None, **kw): 143 193 """ 144 194 Serialize ``obj`` to a JSON formatted ``str``. … … 162 212 163 213 If ``indent`` is a non-negative integer, then JSON array elements and 164 object members will be pretty-printed with that indent level. An indent165 level of 0 will only insert newlines. ``None`` is the most compact214 object members will be pretty-printed with that indent level. An indent 215 level of 0 will only insert newlines. ``None`` is the most compact 166 216 representation. 167 217 … … 170 220 ``(',', ':')`` is the most compact JSON representation. 171 221 222 ``encoding`` is the character encoding for str instances, default is UTF-8. 223 224 ``default(obj)`` is a function that should return a serializable version 225 of obj or raise TypeError. The default simply raises TypeError. 226 172 227 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the 173 228 ``.default()`` method to serialize additional types), specify it with 174 229 the ``cls`` kwarg. 175 230 """ 231 # cached encoder 232 if (skipkeys is False and ensure_ascii is True and 233 check_circular is True and allow_nan is True and 234 cls is None and indent is None and separators is None and 235 encoding == 'utf-8' and default is None and not kw): 236 return _default_encoder.encode(obj) 176 237 if cls is None: 177 238 cls = JSONEncoder … … 179 240 skipkeys=skipkeys, ensure_ascii=ensure_ascii, 180 241 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 181 separators=separators, 242 separators=separators, encoding=encoding, default=default, 182 243 **kw).encode(obj) 183 244 184 def load(fp, encoding=None, cls=None, object_hook=None, **kw): 245 246 _default_decoder = JSONDecoder(encoding=None, object_hook=None) 247 248 249 def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, 250 parse_int=None, parse_constant=None, **kw): 185 251 """ 186 252 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing … … 189 255 If the contents of ``fp`` is encoded with an ASCII based encoding other 190 256 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must 191 be specified. Encodings that are not ASCII based (such as UCS-2) are257 be specified. Encodings that are not ASCII based (such as UCS-2) are 192 258 not allowed, and should be wrapped with 193 259 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` … … 195 261 196 262 ``object_hook`` is an optional function that will be called with the 197 result of any object literal decode (a ``dict``). The return value of198 ``object_hook`` will be used instead of the ``dict``. This feature263 result of any object literal decode (a ``dict``). The return value of 264 ``object_hook`` will be used instead of the ``dict``. This feature 199 265 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 200 266 … … 202 268 kwarg. 203 269 """ 270 return loads(fp.read(), 271 encoding=encoding, cls=cls, object_hook=object_hook, 272 parse_float=parse_float, parse_int=parse_int, 273 parse_constant=parse_constant, **kw) 274 275 276 def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, 277 parse_int=None, parse_constant=None, **kw): 278 """ 279 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON 280 document) to a Python object. 281 282 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding 283 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name 284 must be specified. Encodings that are not ASCII based (such as UCS-2) 285 are not allowed and should be decoded to ``unicode`` first. 286 287 ``object_hook`` is an optional function that will be called with the 288 result of any object literal decode (a ``dict``). The return value of 289 ``object_hook`` will be used instead of the ``dict``. This feature 290 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 291 292 ``parse_float``, if specified, will be called with the string 293 of every JSON float to be decoded. By default this is equivalent to 294 float(num_str). This can be used to use another datatype or parser 295 for JSON floats (e.g. decimal.Decimal). 296 297 ``parse_int``, if specified, will be called with the string 298 of every JSON int to be decoded. By default this is equivalent to 299 int(num_str). This can be used to use another datatype or parser 300 for JSON integers (e.g. float). 301 302 ``parse_constant``, if specified, will be called with one of the 303 following strings: -Infinity, Infinity, NaN, null, true, false. 304 This can be used to raise an exception if invalid JSON numbers 305 are encountered. 306 307 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 308 kwarg. 309 """ 310 if (cls is None and encoding is None and object_hook is None and 311 parse_int is None and parse_float is None and 312 parse_constant is None and not kw): 313 return _default_decoder.decode(s) 204 314 if cls is None: 205 315 cls = JSONDecoder 206 316 if object_hook is not None: 207 317 kw['object_hook'] = object_hook 208 return cls(encoding=encoding, **kw).decode(fp.read()) 209 210 def loads(s, encoding=None, cls=None, object_hook=None, **kw): 211 """ 212 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON 213 document) to a Python object. 214 215 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding 216 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name 217 must be specified. Encodings that are not ASCII based (such as UCS-2) 218 are not allowed and should be decoded to ``unicode`` first. 219 220 ``object_hook`` is an optional function that will be called with the 221 result of any object literal decode (a ``dict``). The return value of 222 ``object_hook`` will be used instead of the ``dict``. This feature 223 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 224 225 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 226 kwarg. 227 """ 228 if cls is None: 229 cls = JSONDecoder 230 if object_hook is not None: 231 kw['object_hook'] = object_hook 318 if parse_float is not None: 319 kw['parse_float'] = parse_float 320 if parse_int is not None: 321 kw['parse_int'] = parse_int 322 if parse_constant is not None: 323 kw['parse_constant'] = parse_constant 232 324 return cls(encoding=encoding, **kw).decode(s) 233 325 326 327 # 328 # Compatibility cruft from other libraries 329 # 330 331 332 def decode(s): 333 """ 334 demjson, python-cjson API compatibility hook. Use loads(s) instead. 335 """ 336 import warnings 337 warnings.warn("simplejson.loads(s) should be used instead of decode(s)", 338 DeprecationWarning) 339 return loads(s) 340 341 342 def encode(obj): 343 """ 344 demjson, python-cjson compatibility hook. Use dumps(s) instead. 345 """ 346 import warnings 347 warnings.warn("simplejson.dumps(s) should be used instead of encode(s)", 348 DeprecationWarning) 349 return dumps(obj) 350 351 234 352 def read(s): 235 353 """ 236 json-py API compatibility hook. Use loads(s) instead. 354 jsonlib, JsonUtils, python-json, json-py API compatibility hook. 355 Use loads(s) instead. 237 356 """ 238 357 import warnings … … 241 360 return loads(s) 242 361 362 243 363 def write(obj): 244 364 """ 245 json-py API compatibility hook. Use dumps(s) instead. 365 jsonlib, JsonUtils, python-json, json-py API compatibility hook. 366 Use dumps(s) instead. 246 367 """ 247 368 import warnings … … 251 372 252 373 374 if __name__ == '__main__': 375 import simplejson.tool 376 simplejson.tool.main() django/branches/gis/django/utils/simplejson/LICENSE.txt
r4454 r8215 1 simplejson 1.52 1 Copyright (c) 2006 Bob Ippolito 3 2 django/branches/gis/django/utils/simplejson/scanner.py
r4454
