1 __all__
= ['seqToKV', 'kvToSeq', 'dictToKV', 'kvToDict']
3 from openid
import oidutil
7 class KVFormError(ValueError):
10 def seqToKV(seq
, strict
=False):
11 """Represent a sequence of pairs of strings as newline-terminated
12 key:value pairs. The pairs are generated in the order given.
15 @type seq: [(str, (unicode|str))]
17 @return: A string representation of the sequence
21 formatted
= 'seqToKV warning: %s: %r' % (msg
, seq
)
23 raise KVFormError(formatted
)
25 oidutil
.log(formatted
)
29 if isinstance(k
, types
.StringType
):
31 elif not isinstance(k
, types
.UnicodeType
):
32 err('Converting key to string: %r' % k
)
37 'Invalid input for seqToKV: key contains newline: %r' % (k
,))
41 'Invalid input for seqToKV: key contains colon: %r' % (k
,))
44 err('Key has whitespace at beginning or end: %r' % (k
,))
46 if isinstance(v
, types
.StringType
):
48 elif not isinstance(v
, types
.UnicodeType
):
49 err('Converting value to string: %r' % (v
,))
54 'Invalid input for seqToKV: value contains newline: %r' % (v
,))
57 err('Value has whitespace at beginning or end: %r' % (v
,))
59 lines
.append(k
+ ':' + v
+ '\n')
61 return ''.join(lines
).encode('UTF8')
63 def kvToSeq(data
, strict
=False):
66 After one parse, seqToKV and kvToSeq are inverses, with no warnings::
69 seqToKV(kvToSeq(seq)) == seq
72 formatted
= 'kvToSeq warning: %s: %r' % (msg
, data
)
74 raise KVFormError(formatted
)
76 oidutil
.log(formatted
)
78 lines
= data
.split('\n')
80 err('Does not end in a newline')
93 pair
= line
.split(':', 1)
98 fmt
= ('In line %d, ignoring leading or trailing '
99 'whitespace in key %r')
100 err(fmt
% (line_num
, k
))
103 err('In line %d, got empty key' % (line_num
,))
107 fmt
= ('In line %d, ignoring leading or trailing '
108 'whitespace in value %r')
109 err(fmt
% (line_num
, v
))
111 pairs
.append((k_s
.decode('UTF8'), v_s
.decode('UTF8')))
113 err('Line %d does not contain a colon' % line_num
)
123 return dict(kvToSeq(s
))