Package grassyknoll :: Package backend :: Package lucene :: Module conversion
[hide private]

Source Code for Module grassyknoll.backend.lucene.conversion

 1  """convert python values to and from L{lucene}""" 
 2   
 3  from lucene import NumberTools 
 4  import time 
 5  import datetime 
 6   
 7  ## Lucene can't store floats natively, so we need to intify. This gives us 6 
 8  ## decimal places of precision 
 9  ## XXX it'd be nice to specify this a per-field basis 
10  _float_scale_factor = float(1e6) 
11   
12  ## Lucene's 
13  ## U{DateTools<http://lucene.apache.org/java/2_2_0/api/org/apache/lucene/document/DateTools.html>} 
14  ## are moronic, so we have our own compatible versions. The automatic timezone 
15  ## conversion is particularly stupid. 
16   
17 -def toLucene(value):
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 # we disallow str, since lucene assumes it's utf8 (I think) 26 if isinstance(value, unicode): 27 return value 28 29 if isinstance(value, (int, long)): 30 value=long(value) # XXX bug in lucene-JCC 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
48 -def fromLucene(value, typ):
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