forked from maxcutler/python-wordpress-xmlrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfieldmaps.py
More file actions
92 lines (73 loc) · 2.91 KB
/
Copy pathfieldmaps.py
File metadata and controls
92 lines (73 loc) · 2.91 KB
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
89
90
91
92
import xmlrpclib
import datetime
class FieldMap(object):
"""
Container for settings mapping a WordPress XML-RPC request/response struct
to a Python, programmer-friendly class.
Parameters:
`inputName`: name of the field in XML-RPC response.
`outputNames`: (optional) list of field names to use when generating new XML-RPC request. defaults to `[inputName]`
`default`: (optional) default value to use when none is supplied in XML-RPC response. defaults to `None`
`conversion`: (optional) function to convert Python value to XML-RPC value for XML-RPC request.
"""
def __init__(self, inputName, outputNames=None, default=None, conversion=None):
self.name = inputName
self.output_names = outputNames or [inputName]
self.default = default
self.conversion = conversion
def convert_to_python(self, xmlrpc=None):
"""
Extracts a value for the field from an XML-RPC response.
"""
if xmlrpc:
return xmlrpc.get(self.name, self.default)
elif self.default:
return self.default
else:
return None
def convert_to_xmlrpc(self, input_value):
"""
Convert a Python value to the expected XML-RPC value type.
"""
if self.conversion:
return self.conversion(input_value)
else:
return input_value
def get_outputs(self, input_value):
"""
Generate a set of output values for a given input.
"""
output_value = self.convert_to_xmlrpc(input_value)
output = {}
for name in self.output_names:
output[name] = output_value
return output
class IntegerFieldMap(FieldMap):
"""
FieldMap pre-configured for handling integer fields.
"""
def __init__(self, *args, **kwargs):
if 'conversion' not in kwargs:
kwargs['conversion'] = int
super(IntegerFieldMap, self).__init__(*args, **kwargs)
class DateTimeFieldMap(FieldMap):
"""
FieldMap pre-configured for handling DateTime fields.
"""
def __init__(self, *args, **kwargs):
if 'conversion' not in kwargs:
kwargs['conversion'] = xmlrpclib.DateTime
super(DateTimeFieldMap, self).__init__(*args, **kwargs)
def convert_to_python(self, xmlrpc=None):
if xmlrpc:
# make sure we have an `xmlrpclib.DateTime` instance
raw_value = xmlrpc.get(self.name, self.default)
if not isinstance(raw_value, xmlrpclib.DateTime):
raw_value = xmlrpclib.DateTime(raw_value)
# extract its timetuple and convert to datetime
tt = raw_value.timetuple()
return datetime.datetime(*tuple(tt)[:6])
elif self.default:
return self.default
else:
return None