Debian Codegraph @

pecan/jsonify.py

raw
1 from datetime import datetime, date
2 from decimal import Decimal
3 from functools import singledispatch
4 from json import JSONEncoder
5
6 from webob.multidict import MultiDict
7
8 try:
9 import sqlalchemy # noqa
10 try:
11 # SQLAlchemy 2.0 support
12 from sqlalchemy.engine import CursorResult as ResultProxy
13 from sqlalchemy.engine import Row as RowProxy
14 except ImportError:
15 from sqlalchemy.engine.result import ResultProxy, RowProxy
16 except ImportError:
17 # dummy classes since we don't have SQLAlchemy installed
18 class ResultProxy(object): # noqa
19 pass
20
21 class RowProxy(object): # noqa
22 pass
23
24 try:
25 from sqlalchemy.engine.cursor import LegacyCursorResult, LegacyRow
26 except ImportError: # pragma no cover
27 # dummy classes since we don't have SQLAlchemy installed
28 # or we're using SQLAlchemy < 1.4
29
30 class LegacyCursorResult(object): # noqa
31 pass
32
33 class LegacyRow(object): # noqa
34 pass
35
36
37 #
38 # encoders
39 #
40
41 def is_saobject(obj):
42 return hasattr(obj, '_sa_class_manager')
43
44
45 class GenericJSON(JSONEncoder):
46 '''
47 Generic JSON encoder. Makes several attempts to correctly JSONify
48 requested response objects.
49 '''
50 def default(self, obj):
51 '''
52 Converts an object and returns a ``JSON``-friendly structure.
53
54 :param obj: object or structure to be converted into a
55 ``JSON``-ifiable structure
56
57 Considers the following special cases in order:
58
59 * object has a callable __json__() attribute defined
60 returns the result of the call to __json__()
61 * date and datetime objects
62 returns the object cast to str
63 * Decimal objects
64 returns the object cast to float
65 * SQLAlchemy objects
66 returns a copy of the object.__dict__ with internal SQLAlchemy
67 parameters removed
68 * SQLAlchemy ResultProxy objects
69 Casts the iterable ResultProxy into a list of tuples containing
70 the entire resultset data, returns the list in a dictionary
71 along with the resultset "row" count.
72
73 .. note:: {'count': 5, 'rows': [('Ed Jones',), ('Pete Jones',),
74 ('Wendy Williams',), ('Mary Contrary',), ('Fred Smith',)]}
75
76 * SQLAlchemy RowProxy objects
77 Casts the RowProxy cursor object into a dictionary, probably
78 losing its ordered dictionary behavior in the process but
79 making it JSON-friendly.
80 * webob.multidict.MultiDict objects
81 returns MultiDict.mixed() dictionary, which is guaranteed
82 to be JSON-friendly.
83 '''
84 if hasattr(obj, '__json__') and callable(obj.__json__):
85 return obj.__json__()
86 elif isinstance(obj, (date, datetime)):
87 return str(obj)
88 elif isinstance(obj, Decimal):
89 # XXX What to do about JSONEncoder crappy handling of Decimals?
90 # SimpleJSON has better Decimal encoding than the std lib
91 # but only in recent versions
92 return float(obj)
93 elif is_saobject(obj):
94 props = {}
95 for key in obj.__dict__:
96 if not key.startswith('_sa_'):
97 props[key] = getattr(obj, key)
98 return props
99 elif isinstance(obj, ResultProxy):
100 props = dict(rows=list(obj), count=obj.rowcount)
101 if props['count'] < 0:
102 props['count'] = len(props['rows'])
103 return props
104 elif isinstance(obj, LegacyCursorResult):
105 rows = [dict(row._mapping) for row in obj.fetchall()]
106 return {'count': len(rows), 'rows': rows}
107 elif isinstance(obj, LegacyRow):
108 return dict(obj._mapping)
109 elif isinstance(obj, RowProxy):
110 if obj.__class__.__name__ == 'Row':
111 # SQLAlchemy 2.0 support
112 obj = obj._mapping
113 return dict(obj)
114 elif isinstance(obj, MultiDict):
115 return obj.mixed()
116 else:
117 return JSONEncoder.default(self, obj)
118
119
120 _default = GenericJSON()
121
122
123 def with_when_type(f):
124 # Add some backwards support for simplegeneric's API
125 f.when_type = f.register
126 return f
127
128
129 @with_when_type
130 @singledispatch
131 def jsonify(obj):
132 return _default.default(obj)
133
134
135 class GenericFunctionJSON(GenericJSON):
136 def default(self, obj):
137 return jsonify(obj)
138
139
140 _instance = GenericFunctionJSON()
141
142
143 def encode(obj):
144 return _instance.encode(obj)