forked from bbmokhtari/django-translations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeautifier.py
88 lines (70 loc) · 2.42 KB
/
beautifier.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from django.db.models import Q, QuerySet
from translations.models import TranslatableQuerySet
def beautify(obj, representation=True):
return beautify_any(obj, '', True, representation)
def beautify_any(obj, base, first, representation):
if isinstance(obj, dict):
return beautify_iter(
obj, base, first,
'{', '}', dict_iterator
)
elif isinstance(obj, list):
return beautify_iter(
obj, base, first,
'[', ']', list_iterator
)
elif isinstance(obj, Q):
if representation:
return beautify_iter(
obj, base, first,
'<Q: ({}:'.format(obj.connector), ')>', q_iterator
)
else:
return beautify_iter(
obj, base, first,
'({}:'.format(obj.connector), ')', q_iterator
)
elif isinstance(obj, TranslatableQuerySet):
return beautify_iter(
obj, base, first,
'<TranslatableQuerySet [', ']>', queryset_iterator
)
elif isinstance(obj, QuerySet):
return beautify_iter(
obj, base, first,
'<QuerySet [', ']>', queryset_iterator
)
else:
if representation:
return repr(obj)
else:
return str(obj)
def dict_iterator(obj, beautifier):
return sorted([
'{key}: {value}'.format(key=beautifier(key), value=beautifier(value))
for key, value in obj.items()
])
def list_iterator(obj, beautifier):
return [beautifier(value) for value in obj]
def q_iterator(obj, beautifier):
return sorted([
beautifier(value, False)
if isinstance(value, Q) else beautifier(value)
for value in obj.children
])
def queryset_iterator(obj, beautifier):
return [beautifier(value) for value in sorted(obj, key=lambda x: x.pk)]
def beautify_iter(obj, base, first, opener, closer, iterator):
indent = base + (4 * ' ')
# items
items = []
def beautifier(value, representation=True):
return beautify_any(value, indent, False, representation)
for item in iterator(obj, beautifier):
items.append(indent + item + ',')
base_opener = (base + opener) if first else opener
if len(items) > 0:
base_closer = base + closer
return '{}\n{}\n{}'.format(base_opener, '\n'.join(items), base_closer)
else:
return '{}{}'.format(base_opener, closer)