1 """convert python values to and from L{lucene}"""
2
3 from lucene import NumberTools
4 import time
5 import datetime
6
7
8
9
10 _float_scale_factor = float(1e6)
11
12
13
14
15
16
18 """
19 @arg value: a value to be intelligently converted
20 @type value: basic Python type
21
22 @returns: a Lucene encoding of value
23 @rtype: unicode
24 """
25
26 if isinstance(value, unicode):
27 return value
28
29 if isinstance(value, (int, long)):
30 value=long(value)
31 return NumberTools.longToString(value)
32
33 if isinstance(value, float):
34 scaled_float = long(value * _float_scale_factor)
35 return NumberTools.longToString(scaled_float)
36
37 if isinstance(value, datetime.datetime):
38 return unicode(value.strftime('%Y%m%d%H%M%S'))
39
40 if isinstance(value, datetime.date):
41 return unicode(value.strftime('%Y%m%d'))
42
43 if isinstance(value, datetime.time):
44 return unicode(value.strftime('%H%M%S'))
45
46 raise TypeError(value)
47
49 """
50 @arg value: a Lucene encoding of value
51 @type value: unicode
52
53 @arg typ: the desired Python type
54 @type typ: type
55
56 @returns: an instance of typ
57 @rtype: typ
58 """
59 if isinstance(value, str):
60 raise TypeError("Lucene does't support decoding str")
61
62 if typ is unicode:
63 return value
64
65 if typ is str:
66 raise TypeError("Lucene doesn't support converting to str")
67
68 if typ is int or typ is long:
69 return NumberTools.stringToLong(value)
70
71 if typ is float:
72 return float(NumberTools.stringToLong(value))/_float_scale_factor
73
74 if typ is datetime.datetime:
75 return datetime.datetime.strptime(value, '%Y%m%d%H%M%S')
76
77 if typ is datetime.date:
78 return datetime.datetime.strptime(value, '%Y%m%d').date()
79
80 if typ is datetime.time:
81 return datetime.datetime.strptime(value, '%H%M%S').time()
82
83 raise TypeError, typ
84