diff --git svarga utils strings py svarga utils strings py --- svarga

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
diff --git a/svarga/utils/strings.py b/svarga/utils/strings.py
--- a/svarga/utils/strings.py
+++ b/svarga/utils/strings.py
@@ -7,3 +7,31 @@ from random import random
def randomize_key(key = ''):
return md5('%s%s%s' % (random(), time(), key))
+
+def makestr(value, encoding='utf-8'):
+ '''Tries to make str, encoded as ``encoding``.'''
+ if isinstance(value, str):
+ return value
+ elif isinstance(value, unicode):
+ return value.encode(encoding)
+ return str(value)
+
+def makeunicode(value, encoding='utf-8', errors='strict'):
+ '''Tries to make unicode, decoding str using ``encoding``.
+
+ To understand ``errors`` parameter, read ``unicode.__doc__``.
+ '''
+ if not isinstance(value, basestring):
+ if hasattr(value, '__unicode__'):
+ return unicode(value)
+ try:
+ try:
+ return unicode(str(value), encoding, errors)
+ except UnicodeEncodeError:
+ if not isinstance(value, Exception):
+ raise
+ # that was captured exception, we shouldn't hide it
+ return ' '.join([makeunicode(arg, encoding, errors)
+ for arg in value])
+ elif not isinstance(value, unicode):
+ return value.decode(encoding, errors)