1 #!/usr/bin/env python 2 3 """ 4 Conversion functions and data used by XML-RPC and SOAP. 5 6 Copyright (C) 2007 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU Lesser General Public License as published by the Free 10 Software Foundation; either version 3 of the License, or (at your option) any 11 later version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 16 details. 17 18 You should have received a copy of the GNU Lesser General Public License along 19 with this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 import datetime 23 24 # Utility classes. 25 26 class ParameterName(object): 27 28 "A method parameter name." 29 30 def __init__(self, ns, name): 31 self.ns = ns 32 self.name = name 33 34 def __eq__(self, other): 35 return self.ns, to_localName(self.name) == other.ns, to_localName(other.name) 36 37 def __hash__(self): 38 return hash(self.ns + to_localName(self.name)) 39 40 def __repr__(self): 41 return "ParameterName(%s, %s)" % (repr(self.ns), repr(self.name or None)) 42 43 class ParameterValue(object): 44 45 "A method parameter value." 46 47 def __init__(self, name, value): 48 self.name = name 49 self.value = value 50 51 def convert(self, converters=None): 52 conv = default_converters 53 conv.update(converters or {}) 54 typename = self.name.ns 55 localName = to_localName(self.name.name) 56 if isinstance(self.value, list): 57 return [item.convert(converters) for item in self.value] 58 else: 59 functions = conv.get(typename, {}) 60 function = functions.get(localName) or functions.get(None, unicode) 61 return function(self.value) 62 63 def _data(self): 64 return self.convert() 65 66 data = property(_data) 67 68 def __eq__(self, other): 69 return self.name == other.name and self.value == other.value 70 71 def __hash__(self): 72 return hash(self.value) 73 74 def __repr__(self): 75 return "ParameterValue(%s, %s)" % (repr(self.name), repr(self.value)) 76 77 # Sequence emulation. 78 79 def __len__(self): 80 return len(self.value) 81 82 def __getitem__(self, i): 83 return self.value[i] 84 85 def to_localName(name): 86 return (name or "").split(":")[-1] or None 87 88 # Utility functions. 89 90 def boolean(s): 91 if s.lower() == "true": 92 return True 93 elif s.lower() == "false": 94 return False 95 else: 96 raise ValueError, "String value %s not convertable to boolean." % repr(s) 97 98 def iso8601(s): 99 # NOTE: To be written. 100 return s 101 102 default_converters = { 103 "string" : {None : unicode}, 104 "int" : {None : int}, 105 "i4" : {None : int}, 106 "double" : {None : float}, 107 "boolean" : {None : boolean}, 108 "dateTime.iso8601" : {None : iso8601}, 109 "base64" : {None : str} 110 } 111 112 # vim: tabstop=4 expandtab shiftwidth=4