4 usage: %(progname)s [args] 76 MAX_RANDOM = sys.maxint
77 rand = random.Random()
79 lock = threading.RLock()
82 ip = socket.gethostbyname(socket.gethostname())
83 except (socket.gaierror):
86 ip +=
'.' + str(rand.randrange(1, 254))
87 hexip =
''.join([
"%04x" % long(i)
for i
in ip.split(
'.')])
88 ipaddrStr = socket.inet_aton(ip)
89 (ipaddr, ) = struct.unpack(
">I", ipaddrStr)
92 if i<10:
return chr(i+48)
93 elif i<38:
return chr(i-10+64)
94 elif i<64:
return chr(i-38+97)
99 for j
in range(bytes):
104 p = string.join(parts,
"")
111 elif n >= 64
and n <= 91:
113 elif n >= 97
and n <= 122:
120 for j
in range(bytes):
143 '''A circular set. A set that maxes at a given size, replacing the oldest element after maximum size. 144 This implementation is NOT thread safe. (generate() below is thread safe, though) 152 '''Adds a value to the queue''' 154 assert not self.queue_map.has_key(val),
'This value is already in the set!' 162 self.queue.append(val)
179 '''Generates a new guid''' 181 if time_t > 1136102400:
182 raise ValueError,
"time_t is too large %s" % time_t
189 t = long(time.time() * 100)
194 r = int(rand.random() * MAX_RANDOM) & 0xffff
195 n = 0L | (long(t)<<48) | (ipaddr<<16) | r
196 guid =
pack64(n, bytes=16)
201 except AssertionError:
206 InvalidGUID =
"Invalid GUID" 209 '''Extracts the time portion out of the guid and returns the 210 number of seconds since the epoch as a float''' 211 if len(guid) != 16:
raise InvalidGUID
213 t = long(n >> 48) / 100
218 '''Extracts the ip portion out of the guid and returns it 219 as a string like 10.10.10.10''' 221 if len(guid) != 16:
raise InvalidGUID
227 ip = struct.pack(
">L", n)
228 ipaddrStr = socket.inet_ntoa(ip)
233 '''Extracts the random bits from the guid (returns the bits in decimal)''' 234 if len(guid) != 16:
raise InvalidGUID
246 print __doc__ % vars()
248 def main(argv, stdout, environ):
250 optlist, args = getopt.getopt(argv[1:],
"", [
"help",
"test",
"debug"])
254 for (field, val)
in optlist:
255 if field ==
"--help":
258 elif field ==
"--debug":
260 elif field ==
"--test":
276 print "Time:", time.strftime(
'%a, %d %b %Y %H:%M:%S', time.localtime(
extract_time(guid)))
282 if __name__ ==
"__main__":
283 main(sys.argv, sys.stdout, os.environ)
def main(argv, stdout, environ)
def test()
TESTING OF GUID CLASS ###.
def generate(time_t=None)
Public module functions.
A simple circular set to ensure we don't duplicate GUIDs in the same millisecond. ...