On 4/13/2016 9:55 PM, Aline Manera wrote:
On 04/13/2016 01:11 AM, archus(a)linux.vnet.ibm.com wrote:
> From: Archana Singh <archus(a)linux.vnet.ibm.com>
>
> Added two utils methods which can be used to convert
> String to Unicode and Unicode to String.
> This method does the checking of instance of value passed
> and accordingly used the encode, decode, str methods.
>
> Signed-off-by: Archana Singh <archus(a)linux.vnet.ibm.com>
> ---
> src/wok/utils.py | 24 ++++++++++++++++++++++++
> 1 file changed, 24 insertions(+)
>
> diff --git a/src/wok/utils.py b/src/wok/utils.py
> index 175cf25..0e8ec05 100644
> --- a/src/wok/utils.py
> +++ b/src/wok/utils.py
> @@ -622,3 +622,27 @@ def upgrade_objectstore_schema(objstore=None,
> field=None):
> wok_log.error("Cannot upgrade objectstore schema: %s" %
> e.args[0])
> return False
> return True
> +
> +
> +def encode_value(val):
> + """
> + Convert the value to string.
> + If its unicode, use encode otherwise str.
> + """
> + if isinstance(val, unicode):
> + return val.encode('utf-8')
> + return str(val)
> +
> +
> +def decode_value(val):
> + """
> + Converts value to unicode,
> + if its not an instance of unicode.
> + For doing so convert the val to string,
> + if its not instance of basestring.
> + """
> + if not isinstance(val, basestring):
> + val = str(val)
Could you give an example when the above if condition is used?
For eg. this method
can be used to convert integer to unicode, by first
converting it to string. And another example can be when exception
string(i.e str(e)) has to be converted to unicode and if it has some
non-ascii encoded value.
"isinstance" of "basestring" is nothing but "isinstance" of
"String" or
"unicode". So basically if pass a value which is not instance of
"basestring" then first has to be converted to "String", as decode can
be called on "String" instance only.
> + if not isinstance(val, unicode):
> + val = val.decode('utf-8')
> + return val