/
monkey_patch_colander.py
70 lines (51 loc) · 1.96 KB
/
monkey_patch_colander.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
'''
Created on Feb 27, 2013
Patching the result of the following 4 functions, to generate
proper JSON output:
Boolean.serialize()
Int.serialize()
Float.serialize()
MappingSchema.serialize()
Obtained from: https://github.com/Pylons/colander/issues/80
'''
import colander
def apply():
pass
# Recover boolean values which were coerced into strings.
serialize_boolean = getattr(colander.Boolean, 'serialize')
def patched_boolean_serialization(*args, **kwds):
result = serialize_boolean(*args, **kwds)
if result is not colander.null:
result = result == 'true'
return result
setattr(colander.Boolean, 'serialize', patched_boolean_serialization)
# Recover float values which were coerced into strings.
serialize_float = getattr(colander.Float, 'serialize')
def patched_float_serialization(*args, **kwds):
result = serialize_float(*args, **kwds)
if result is not colander.null:
result = float(result)
return result
setattr(colander.Float, 'serialize', patched_float_serialization)
# Recover integer values which were coerced into strings.
serialize_int = getattr(colander.Int, 'serialize')
def patched_int_serialization(*args, **kwds):
result = serialize_int(*args, **kwds)
if result is not colander.null:
result = int(result)
return result
setattr(colander.Int, 'serialize', patched_int_serialization)
#
# # Remove optional mapping keys which were associated with 'colander.null'.
# serialize_mapping = getattr(colander.MappingSchema, 'serialize')
#
# def patched_mapping_serialization(*args, **kwds):
# result = serialize_mapping(*args, **kwds)
#
# if result is not colander.null:
# result = {k: v for k, v in result.iteritems()
# if v is not colander.null}
#
# return result
#
# setattr(colander.MappingSchema, 'serialize', patched_mapping_serialization)