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 | def default(self, obj): |
---|
23 | # Convert objects to a dictionary of their representation |
---|
24 | d = { '__module__':obj.__module__, |
---|
25 | } |
---|
26 | if obj.__class__.__name__ == 'EnumSymbol': |
---|
27 | d['__class__'] = obj._cls.__name__ |
---|
28 | else: |
---|
29 | d['__class__'] = obj.__class__.__name__ |
---|
30 | |
---|
31 | if d['__module__'].startswith('sqlalchemy'): |
---|
32 | return d |
---|
33 | |
---|
34 | if d['__class__'] == 'Decimal': |
---|
35 | d.update({'value': str(obj)}) |
---|
36 | else: |
---|
37 | for key in obj.__dict__.keys(): |
---|
38 | if not (key.startswith("_") or self.__pattern.match(key) or self.__pattern2.match(key)): |
---|
39 | d.update({key: getattr(obj, key)}) |
---|
40 | getters = list(methodsWithDecorator(type(obj), "property")) |
---|
41 | for name in getters: |
---|
42 | try: |
---|
43 | d.update({name: getattr(obj, name)}) |
---|
44 | except Exception as e: |
---|
45 | DJEncoder.log.error(e) |
---|
46 | |
---|
47 | for key, value in d.items(): |
---|
48 | if value is not None and id(value) in self.__markers and not isinstance(value, str) and not isinstance(value, int): |
---|
49 | continue |
---|
50 | #return {} |
---|
51 | else: |
---|
52 | self.__markers[id(value)] = value |
---|
53 | ''' |
---|
54 | if isinstance(value, str) or isinstance(value, unicode): |
---|
55 | self.__markers[id(value)] = escapeForJSON(value) |
---|
56 | else: |
---|
57 | self.__markers[id(value)] = value |
---|
58 | ''' |
---|
59 | return d |
---|
60 | |
---|
61 | def encodeToJSON(toEncode): |
---|
62 | return escapeForJSON(DJEncoder().encode(toEncode)) |
---|
63 | |
---|
64 | def escapeForJSON(toEscape): |
---|
65 | res = toEscape.replace('"', '"') |
---|
66 | res = res.replace("'", "'") |
---|
67 | #res = res.replace("'", "'") |
---|
68 | res = res.replace('\\', '\\') |
---|
69 | #res = res.replace('(', '(') |
---|
70 | #res = res.replace(')', ')') |
---|
71 | return res |
---|