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 other_ns, other_name = other 36 return self.ns, to_localName(self.name) == other_ns, to_localName(other_name) 37 38 def __hash__(self): 39 return hash(self.ns + to_localName(self.name)) 40 41 def __repr__(self): 42 return "ParameterName(%s, %s)" % (repr(self.ns), repr(self.name or None)) 43 44 # Sequence emulation. 45 46 def __len__(self): 47 return 2 48 49 def __getitem__(self, i): 50 return (self.ns, self.name)[i] 51 52 def to_localName(name): 53 return (name or "").split(":")[-1] or None 54 55 def convert(parameters, converters=None): 56 57 """ 58 Convert the 'parameters', returning a list of name, value items where the 59 names are the plain names for each parameter, and the values may be 60 converted from strings to other data types. 61 """ 62 63 conv = default_converters 64 conv.update(converters or {}) 65 results = [] 66 for parameter_name, parameter_value in parameters: 67 typename, name = parameter_name 68 localName = to_localName(name) 69 if isinstance(parameter_value, list): 70 value = convert(parameter_value, converters) 71 else: 72 functions = conv.get(typename, {}) 73 function = functions.get(localName) or functions.get(None, unicode) 74 value = function(parameter_value) 75 results.append((localName, value)) 76 return results 77 78 # Utility functions. 79 80 def boolean(s): 81 if s.lower() == "true": 82 return True 83 elif s.lower() == "false": 84 return False 85 else: 86 raise ValueError, "String value %s not convertable to boolean." % repr(s) 87 88 def iso8601(s): 89 # NOTE: To be written. 90 return s 91 92 default_converters = { 93 "string" : {None : unicode}, 94 "int" : {None : int}, 95 "i4" : {None : int}, 96 "double" : {None : float}, 97 "boolean" : {None : boolean}, 98 "dateTime.iso8601" : {None : iso8601}, 99 "base64" : {None : str} 100 } 101 102 # vim: tabstop=4 expandtab shiftwidth=4