[utils] the json module is always available

It's included since python 2.6, and we don't support earlier versions.

authorJulien Cristau <julien.cristau@logilab.fr>
changesetb5abcda42163
branchdefault
phasedraft
hiddenyes
parent revision#e8b9a3d23ad9 [web/request] deprecate user_callback
child revision<not specified>
files modified by this revision
utils.py
# HG changeset patch
# User Julien Cristau <julien.cristau@logilab.fr>
# Date 1394792295 -3600
# Fri Mar 14 11:18:15 2014 +0100
# Node ID b5abcda42163bfce164390c194358da33ae2894a
# Parent e8b9a3d23ad93e47391fe566012812245f2a751b
[utils] the json module is always available

It's included since python 2.6, and we don't support earlier versions.

diff --git a/utils.py b/utils.py
@@ -24,10 +24,11 @@
1  import sys
2  import decimal
3  import datetime
4  import random
5  import re
6 +import json
7 
8  from operator import itemgetter
9  from inspect import getargspec
10  from itertools import repeat
11  from uuid import uuid4
@@ -37,10 +38,11 @@
12 
13  from logging import getLogger
14 
15  from logilab.mtconverter import xml_escape
16  from logilab.common.deprecation import deprecated
17 +from logilab.common.date import ustrftime
18 
19  _MARKER = object()
20 
21  # initialize random seed from current time
22  random.seed()
@@ -463,81 +465,70 @@
23          return u'%s\n%s\n%s\n%s\n</html>' % (self.doctype,
24                                               self.htmltag,
25                                               self.head.getvalue(),
26                                               self.body.getvalue())
27 
28 -try:
29 -    # may not be there if cubicweb-web not installed
30 -    if sys.version_info < (2, 6):
31 -        import simplejson as json
32 -    else:
33 -        import json
34 -except ImportError:
35 -    json_dumps = JSString = None
36 
37 -else:
38 -    from logilab.common.date import ustrftime
39 -
40 -    class CubicWebJsonEncoder(json.JSONEncoder):
41 -        """define a json encoder to be able to encode yams std types"""
42 +class CubicWebJsonEncoder(json.JSONEncoder):
43 +    """define a json encoder to be able to encode yams std types"""
44 
45 -        def default(self, obj):
46 -            if hasattr(obj, '__json_encode__'):
47 -                return obj.__json_encode__()
48 -            if isinstance(obj, datetime.datetime):
49 -                return ustrftime(obj, '%Y/%m/%d %H:%M:%S')
50 -            elif isinstance(obj, datetime.date):
51 -                return ustrftime(obj, '%Y/%m/%d')
52 -            elif isinstance(obj, datetime.time):
53 -                return obj.strftime('%H:%M:%S')
54 -            elif isinstance(obj, datetime.timedelta):
55 -                return (obj.days * 24 * 60 * 60) + obj.seconds
56 -            elif isinstance(obj, decimal.Decimal):
57 -                return float(obj)
58 -            try:
59 -                return json.JSONEncoder.default(self, obj)
60 -            except TypeError:
61 -                # we never ever want to fail because of an unknown type,
62 -                # just return None in those cases.
63 -                return None
64 +    def default(self, obj):
65 +        if hasattr(obj, '__json_encode__'):
66 +            return obj.__json_encode__()
67 +        if isinstance(obj, datetime.datetime):
68 +            return ustrftime(obj, '%Y/%m/%d %H:%M:%S')
69 +        elif isinstance(obj, datetime.date):
70 +            return ustrftime(obj, '%Y/%m/%d')
71 +        elif isinstance(obj, datetime.time):
72 +            return obj.strftime('%H:%M:%S')
73 +        elif isinstance(obj, datetime.timedelta):
74 +            return (obj.days * 24 * 60 * 60) + obj.seconds
75 +        elif isinstance(obj, decimal.Decimal):
76 +            return float(obj)
77 +        try:
78 +            return json.JSONEncoder.default(self, obj)
79 +        except TypeError:
80 +            # we never ever want to fail because of an unknown type,
81 +            # just return None in those cases.
82 +            return None
83 
84 -    def json_dumps(value, **kwargs):
85 -        return json.dumps(value, cls=CubicWebJsonEncoder, **kwargs)
86 +def json_dumps(value, **kwargs):
87 +    return json.dumps(value, cls=CubicWebJsonEncoder, **kwargs)
88 
89 
90 -    class JSString(str):
91 -        """use this string sub class in values given to :func:`js_dumps` to
92 -        insert raw javascript chain in some JSON string
93 -        """
94 +class JSString(str):
95 +    """use this string sub class in values given to :func:`js_dumps` to
96 +    insert raw javascript chain in some JSON string
97 +    """
98 
99 -    def _dict2js(d, predictable=False):
100 -        res = [key + ': ' + js_dumps(val, predictable)
101 -               for key, val in d.iteritems()]
102 -        return '{%s}' % ', '.join(res)
103 +def _dict2js(d, predictable=False):
104 +    res = [key + ': ' + js_dumps(val, predictable)
105 +           for key, val in d.iteritems()]
106 +    return '{%s}' % ', '.join(res)
107 
108 -    def _list2js(l, predictable=False):
109 -        return '[%s]' % ', '.join([js_dumps(val, predictable) for val in l])
110 +def _list2js(l, predictable=False):
111 +    return '[%s]' % ', '.join([js_dumps(val, predictable) for val in l])
112 
113 -    def js_dumps(something, predictable=False):
114 -        """similar as :func:`json_dumps`, except values which are instances of
115 -        :class:`JSString` are expected to be valid javascript and will be output
116 -        as is
117 +def js_dumps(something, predictable=False):
118 +    """similar as :func:`json_dumps`, except values which are instances of
119 +    :class:`JSString` are expected to be valid javascript and will be output
120 +    as is
121 
122 -        >>> js_dumps({'hop': JSString('$.hop'), 'bar': None}, predictable=True)
123 -        '{bar: null, hop: $.hop}'
124 -        >>> js_dumps({'hop': '$.hop'})
125 -        '{hop: "$.hop"}'
126 -        >>> js_dumps({'hip': {'hop': JSString('momo')}})
127 -        '{hip: {hop: momo}}'
128 -        """
129 -        if isinstance(something, dict):
130 -            return _dict2js(something, predictable)
131 -        if isinstance(something, list):
132 -            return _list2js(something, predictable)
133 -        if isinstance(something, JSString):
134 -            return something
135 -        return json_dumps(something)
136 +    >>> js_dumps({'hop': JSString('$.hop'), 'bar': None}, predictable=True)
137 +    '{bar: null, hop: $.hop}'
138 +    >>> js_dumps({'hop': '$.hop'})
139 +    '{hop: "$.hop"}'
140 +    >>> js_dumps({'hip': {'hop': JSString('momo')}})
141 +    '{hip: {hop: momo}}'
142 +    """
143 +    if isinstance(something, dict):
144 +        return _dict2js(something, predictable)
145 +    if isinstance(something, list):
146 +        return _list2js(something, predictable)
147 +    if isinstance(something, JSString):
148 +        return something
149 +    return json_dumps(something)
150 
151  PERCENT_IN_URLQUOTE_RE = re.compile(r'%(?=[0-9a-fA-F]{2})')
152  def js_href(javascript_code):
153      """Generate a "javascript: ..." string for an href attribute.
154