From b5c049ae2e62f24c6dfce618b94f567671e238ea Mon Sep 17 00:00:00 2001 From: Martin Kosek Date: Wed, 9 Nov 2011 14:10:08 +0100 Subject: Allow custom server backend encoding Server framework does not support encoding of native Python type values stored in Param classes and sub-classes. When backend (LDAP) value encoding differs from Python type value representation user has to has to hard-code the encoders in his processing. This patch introduces a method Param.encode which is used in server context to encode native Python Param values. The new encode method is used for Bool parameter to convert native Python bool type value (True, False) to LDAP value ("TRUE", "FALSE"). https://fedorahosted.org/freeipa/ticket/2039 --- ipalib/parameters.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'ipalib/parameters.py') diff --git a/ipalib/parameters.py b/ipalib/parameters.py index f9e171b0e..1f3fdfde7 100644 --- a/ipalib/parameters.py +++ b/ipalib/parameters.py @@ -307,6 +307,7 @@ class Param(ReadOnly): ('multivalue', bool, False), ('primary_key', bool, False), ('normalizer', callable, None), + ('encoder', callable, None), ('default_from', DefaultFrom, None), ('create_default', callable, None), ('autofill', bool, False), @@ -768,6 +769,34 @@ class Param(ReadOnly): rule=rule, ) + def encode(self, value): + """ + Encode Python native type value to chosen backend format. Encoding is + applied for parameters representing actual attributes (attribute=True). + + The default encode method `Param._encode` can be overriden in a `Param` + instance with `encoder` attribute: + + >>> s = Str('my_str', encoder=lambda x:encode(x)) + + Note that the default method of encoding values is defined in + `Param._encode()`. + + :param value: Encoded value + """ + if not self.attribute: #pylint: disable=E1101 + return value + if self.encoder is not None: #pylint: disable=E1101 + return self.encoder(value) #pylint: disable=E1101 + + return self._encode(value) + + def _encode(self, value): + """ + Encode a value to backend format. + """ + return value + def get_default(self, **kw): """ Return the static default or construct and return a dynamic default. -- cgit