Python 7.0pl5 Benutzerhandbuch

Seite von 124
Message Encoding
84
To add a new mapping at global scope the functions "
encoder()
" and "
decoder()
" should be
used to register functions to do the appropriate conversions. When registering the encoder, the first ar-
gument should be either the type object or class object as appropriate. When registering the decoder,
the first argument should be the qualified name you have given the type.
The encoder function which you register should accept a single argument, that being an instance of
your type. The function should return a tuple containing the qualified name you have given the type
and the value encoded as a string. The decoder function should accept two arguments, they being the
qualified name you have given the type and the value encoded as a string. The function should return
the corresponding instance of the type as described by the encoded value. If the encoded value is
invalid, the function should raise an appropriate exception.
def _encode_Complex(object):
return ("python:complex",repr(object))
def _decode_Complex(name,string):
object = eval(string,{},{})
if type(object) != types.ComplexType:
raise TypeError("invalid encoding for complex type")
return object
netsvc.encoder(types.ComplexType,_encode_Complex)
netsvc.decoder("python:complex",_decode_Complex)
To define a mapping which applies only within the context of a single service, you need to override
the member functions "
encodeObject()
" and "
decodeValue()
" as appropriate. Note that the
default implementations of these methods will apply any global mappings which are present. If your
version of these functions, don’t identify the type you are interested in, your function should call the
base class version of the function. The arguments to these functions are similar to the global encoders
and decoders.
class Database(netsvc.Service):
def __init__(self,name,**kw):
netsvc.Service.__init__(self,name)
# ...
def encodeObject(self,object):
if hasattr(MySQLdb,"DateTime"):
if type(object) == MySQLdb.DateTimeType:
return ("xsd:string",object.strftime())
elif type(object) == MySQLdb.DateTimeDeltaType:
return ("xsd:string",str(object))
return netsvc.Service.encodeObject(self,object)
Providing a mapping which is specific to a service is most often used when the service interacts with
a Python module which defines its own types for such values as date and time. In this circumstance,
the mapping function can automatically translate an instance of the type into a type appropriate for the
encoded data. This avoids your own code having to manually translate values into corresponding val-