Update for an Issue #352

This commit is contained in:
Miroslav Stampar
2013-03-11 14:58:05 +01:00
parent d6fc10092f
commit db0a1e58b9
11 changed files with 138 additions and 8 deletions

View File

@@ -13,12 +13,33 @@ from lib.core.settings import IS_WIN
from lib.core.settings import UNICODE_ENCODING
def base64decode(value):
"""
Decodes string value from Base64 to plain format
>>> base64decode('Zm9vYmFy')
'foobar'
"""
return value.decode("base64")
def base64encode(value):
"""
Encodes string value from plain to Base64 format
>>> base64encode('foobar')
'Zm9vYmFy'
"""
return value.encode("base64")[:-1].replace("\n", "")
def base64pickle(value):
"""
Serializes (with pickle) and encodes to Base64 format supplied (binary) value
>>> base64pickle('foobar')
'gAJVBmZvb2JhcnEALg=='
"""
retVal = None
try:
retVal = base64encode(pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
@@ -31,21 +52,42 @@ def base64pickle(value):
return retVal
def base64unpickle(value):
"""
Decodes value from Base64 to plain format and deserializes (with pickle) it's content
>>> base64unpickle('gAJVBmZvb2JhcnEALg==')
'foobar'
"""
return pickle.loads(base64decode(value))
def hexdecode(value):
"""
Decodes string value from hex to plain format
>>> hexdecode('666f6f626172')
'foobar'
"""
value = value.lower()
return (value[2:] if value.startswith("0x") else value).decode("hex")
def hexencode(value):
"""
Encodes string value from plain to hex format
>>> hexencode('foobar')
'666f6f626172'
"""
return utf8encode(value).encode("hex")
def unicodeencode(value, encoding=None):
"""
Return 8-bit string representation of the supplied unicode value:
Returns 8-bit string representation of the supplied unicode value
>>> unicodeencode(u'test')
'test'
>>> unicodeencode(u'foobar')
'foobar'
"""
retVal = value
@@ -57,16 +99,33 @@ def unicodeencode(value, encoding=None):
return retVal
def utf8encode(value):
"""
Returns 8-bit string representation of the supplied UTF-8 value
>>> utf8encode(u'foobar')
'foobar'
"""
return unicodeencode(value, "utf-8")
def utf8decode(value):
"""
Returns UTF-8 representation of the supplied 8-bit string representation
>>> utf8decode('foobar')
u'foobar'
"""
return value.decode("utf-8")
def htmlescape(value):
codes = (('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ('"', '&quot;'), ("'", '&#39;'), (' ', '&nbsp;'))
return reduce(lambda x, y: x.replace(y[0], y[1]), codes, value)
def htmlunescape(value):
"""
Returns (basic conversion) HTML unescaped value
>>> htmlunescape('a&lt;b')
'a<b'
"""
retVal = value
if value and isinstance(value, basestring):
codes = (('&lt;', '<'), ('&gt;', '>'), ('&quot;', '"'), ('&nbsp;', ' '), ('&amp;', '&'))
@@ -103,7 +162,21 @@ def stdoutencode(data):
return retVal
def jsonize(data):
"""
Returns JSON serialized data
>>> jsonize({'foo':'bar'})
'{\\n "foo": "bar"\\n}'
"""
return json.dumps(data, sort_keys=False, indent=4)
def dejsonize(data):
"""
Returns JSON deserialized data
>>> dejsonize('{\\n "foo": "bar"\\n}')
{u'foo': u'bar'}
"""
return json.loads(data)