1 | ''' |
---|
2 | Created on 9 Feb 2012 |
---|
3 | |
---|
4 | @author: mnagni |
---|
5 | ''' |
---|
6 | from json.encoder import JSONEncoder |
---|
7 | from MolesManager.forms.date import methodsWithDecorator |
---|
8 | import re |
---|
9 | import logging |
---|
10 | |
---|
11 | class DJEncoder(JSONEncoder): |
---|
12 | |
---|
13 | log = logging.getLogger('DJEncoder') |
---|
14 | |
---|
15 | def __init__(self): |
---|
16 | self.__markers = {} |
---|
17 | super(DJEncoder, self).__init__() |
---|
18 | self.__pattern = re.compile('\D\D__*') |
---|
19 | self.__pattern2 = re.compile('\A\w+__id\Z') |
---|
20 | |
---|
21 | |
---|
22 | |
---|
23 | def default(self, obj): |
---|
24 | # Convert objects to a dictionary of their representation |
---|
25 | d = { '__module__':obj.__module__, |
---|
26 | } |
---|
27 | if obj.__class__.__name__ == 'EnumSymbol': |
---|
28 | d['__class__'] = obj._cls.__name__ |
---|
29 | else: |
---|
30 | d['__class__'] = obj.__class__.__name__ |
---|
31 | |
---|
32 | if d['__module__'].startswith('sqlalchemy'): |
---|
33 | return d |
---|
34 | |
---|
35 | if d['__class__'] == 'Decimal': |
---|
36 | d.update({'value': str(obj)}) |
---|
37 | else: |
---|
38 | for key in obj.__dict__.keys(): |
---|
39 | if not (key.startswith("_") or self.__pattern.match(key) or self.__pattern2.match(key)): |
---|
40 | d.update({key: getattr(obj, key)}) |
---|
41 | getters = list(methodsWithDecorator(type(obj), "property")) |
---|
42 | for name in getters: |
---|
43 | try: |
---|
44 | d.update({name: getattr(obj, name)}) |
---|
45 | except Exception as e: |
---|
46 | DJEncoder.log.error(e) |
---|
47 | |
---|
48 | for key, value in d.items(): |
---|
49 | if value is not None and id(value) in self.__markers and not isinstance(value, str) and not isinstance(value, int): |
---|
50 | continue |
---|
51 | #return {} |
---|
52 | else: |
---|
53 | self.__markers[id(value)] = value |
---|
54 | return d |
---|
55 | |
---|
56 | @classmethod |
---|
57 | def escapeForJSON(self, toEscape): |
---|
58 | res = toEscape.replace("'", "'") |
---|
59 | #res = res.replace('"', '\\"') |
---|
60 | res = res.replace('\\', '\\\\') |
---|
61 | return res |
---|
62 | |
---|