commit-gnue
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[gnue] r8396 - in trunk: gnue-appserver/src gnue-appserver/src/gcd gnue-


From: johannes
Subject: [gnue] r8396 - in trunk: gnue-appserver/src gnue-appserver/src/gcd gnue-appserver/src/gld gnue-common/src/utils
Date: Sun, 9 Apr 2006 12:18:41 -0500 (CDT)

Author: johannes
Date: 2006-04-09 12:18:40 -0500 (Sun, 09 Apr 2006)
New Revision: 8396

Modified:
   trunk/gnue-appserver/src/data.py
   trunk/gnue-appserver/src/gcd/readgcd.py
   trunk/gnue-appserver/src/gld/readgld.py
   trunk/gnue-common/src/utils/uuid.py
Log:
Changed detection of hardware addresses (for network interfaces) to also 
support Mac OS X. Pep8-ified utils/uuid.py


Modified: trunk/gnue-appserver/src/data.py
===================================================================
--- trunk/gnue-appserver/src/data.py    2006-04-08 13:49:44 UTC (rev 8395)
+++ trunk/gnue-appserver/src/data.py    2006-04-09 17:18:40 UTC (rev 8396)
@@ -822,9 +822,9 @@
     checktype (table, unicode)
 
     if self.__uuidType == 'time':
-      row = UUID.generateTimeBased ()
+      row = UUID.generate_time_based ()
     else:
-      row = UUID.generateRandom ()
+      row = UUID.generate_random ()
 
     self.__cache.insertRecord (table, row)
     r = record (self.__cache, self.__connections, self.__database, table, row)

Modified: trunk/gnue-appserver/src/gcd/readgcd.py
===================================================================
--- trunk/gnue-appserver/src/gcd/readgcd.py     2006-04-08 13:49:44 UTC (rev 
8395)
+++ trunk/gnue-appserver/src/gcd/readgcd.py     2006-04-09 17:18:40 UTC (rev 
8396)
@@ -1166,9 +1166,9 @@
     """
 
     if self._uuidType == 'time':
-      return UUID.generateTimeBased ()
+      return UUID.generate_time_based ()
     else:
-      return UUID.generateRandom ()
+      return UUID.generate_random ()
 
 
 if __name__ == "__main__":

Modified: trunk/gnue-appserver/src/gld/readgld.py
===================================================================
--- trunk/gnue-appserver/src/gld/readgld.py     2006-04-08 13:49:44 UTC (rev 
8395)
+++ trunk/gnue-appserver/src/gld/readgld.py     2006-04-09 17:18:40 UTC (rev 
8396)
@@ -807,9 +807,9 @@
     """
 
     if self._uuidtype == 'time':
-      return UUID.generateTimeBased ()
+      return UUID.generate_time_based ()
     else:
-      return UUID.generateRandom ()
+      return UUID.generate_random ()
 
 
 # =============================================================================

Modified: trunk/gnue-common/src/utils/uuid.py
===================================================================
--- trunk/gnue-common/src/utils/uuid.py 2006-04-08 13:49:44 UTC (rev 8395)
+++ trunk/gnue-common/src/utils/uuid.py 2006-04-09 17:18:40 UTC (rev 8396)
@@ -20,15 +20,19 @@
 # - Suite 330, Boston, MA 02111-1307, USA.
 #
 # $Id$
+"""
+This module implements an UUID generator as described in the internet draft at
+'http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-05.txt' or also
+described in the RPC-RFC.  
+"""
 
 import sys
 import os
-import string
+import os.path
 import random
 import array
 import threading
 import time
-import types
 import md5
 import sha
 import socket
@@ -36,35 +40,35 @@
 
 from gnue.common.apps import errors
 
-if sys.platform == 'win32':
-  try:
-    from win32com.client import GetObject
-    _HAS_GETOBJECT = True
+try:
+    if sys.platform == 'win32':
+        from win32com.client import GetObject
+    else:
+        import fcntl
 
-  except ImportError:
-    _HAS_GETOBJECT = False
+except ImportError:
+    pass
 
-else:
-  import fcntl
-
 # =============================================================================
 # Exceptions
 # =============================================================================
 
-class InvalidVersionError (errors.SystemError):
-  def __init__ (self, version):
-    msg = u_("The version '%s' is not a valid UUID version") % repr (version)
-    errors.SystemError.__init__ (self, msg)
+class InvalidVersionError(errors.SystemError):
+    def __init__(self, version):
+        msg = u_("The version '%s' is not a valid UUID version") \
+              % repr(version)
+        errors.SystemError.__init__(self, msg)
 
 class InvalidNamespaceError (errors.SystemError):
-  def __init__ (self, ns):
-    msg = u_("'%s' is not recognized as valid namespace argument") % repr (ns)
-    errors.SystemError.__init__ (self, msg)
+    def __init__ (self, ns):
+        msg = u_("'%s' is not recognized as valid namespace argument") \
+              % repr(ns)
+        errors.SystemError.__init__(self, msg)
 
-class MissingNamespaceError (errors.ApplicationError):
-  def __init__ (self):
-    msg = u_("No namespace given for namebased UUID generation")
-    errors.ApplicationError.__init__ (self, msg)
+class MissingNamespaceError(errors.ApplicationError):
+    def __init__(self):
+        msg = u_("No namespace given for namebased UUID generation")
+        errors.ApplicationError.__init__(self, msg)
 
 
 # =============================================================================
@@ -72,240 +76,240 @@
 # =============================================================================
 
 dev_random = None
-pseudoRng  = random.Random ()
-lock       = threading.Lock ()
-manualLock = sys.version_info [:2] < (2, 3)
+pseudoRng  = random.Random()
+lock       = threading.Lock()
+manualLock = sys.version_info[:2] < (2, 3)
 
-if sys.platform == 'linux2':
-  try:
-    dev_random = os.open ('/dev/urandom', os.O_RDONLY)
+if os.path.exists('/dev/urandom'):
+    try:
+        dev_random = os.open('/dev/urandom', os.O_RDONLY)
 
-  except IOError:
-    pass
+    except IOError:
+        pass
 
 
 # -----------------------------------------------------------------------------
 # Get a sequence of random bytes
 # -----------------------------------------------------------------------------
 
-def getRandomBytes (count):
-  """
-  This function returns a sequence of 'count' random bytes from the best random
-  number generator available.
+def getRandomBytes(count):
+    """
+    Return a sequence of 'count' random bytes from the best random number
+    generator available.
 
-  @param count: number of bytes to return
-  @return: sequence of 'count' random bytes
-  """
+    @param count: number of bytes to return
+    @return: sequence of 'count' random bytes
+    """
 
-  result = []
+    result = []
 
-  # If there's a random device we prefer this source
-  if dev_random is not None:
-    lock.acquire ()
+    # If there's a random device we prefer this source
+    if dev_random is not None:
+        lock.acquire()
 
-    while len (result) < count:
-      rdata = os.read (dev_random, count - len (result))
-      result.extend (array.array ('B', rdata).tolist ())
+        while len(result) < count:
+            rdata = os.read(dev_random, count - len(result))
+            result.extend(array.array('B', rdata).tolist())
 
-    lock.release ()
+        lock.release()
 
-  # otherwise use the random module (which is threadsafe for python 2.3+)
-  else:
-    for i in xrange (count):
-      if manualLock: lock.acquire ()
-      result.append (pseudoRng.randrange (0, 256))
-      if manualLock: lock.release ()
+    # otherwise use the random module (which is threadsafe for python 2.3+)
+    else:
+        for i in xrange(count):
+            if manualLock: lock.acquire()
+            result.append (pseudoRng.randrange(0, 256))
+            if manualLock: lock.release()
 
-  return result
+    return result
 
 
-
 # =============================================================================
-# Class implementing an interface to NIC information (hwaddresses)
+# Get the hardware addresses of the installed network interfaces
 # =============================================================================
 
-class NICInformation:
+class NetworkInterfaces:
+    """
+    Retrieve a list of all available network interfaces and their hardware
+    addresses. After creating an instance of this class the attribute nics is a
+    sequence of tuples (name, hwaddr, hwstr) where name is the name of the
+    interface, hwaddr is a list of integers and hwstr is the string
+    representation of the hardware-address.
 
-  SIOCGIFCONF   = 0x8912            # get interface list
-  SIOCGIFHWADDR = 0x8927            # get hardware address
+    On systems identifying as 'linux2' the proc-filesystem will be searched for
+    interface information first. If that fails (or isn't available) we try to
+    get a list of interfaces via sockets.
 
-  # ---------------------------------------------------------------------------
-  # Constructor
-  # ---------------------------------------------------------------------------
+    On OS X the NetworkInterfaces.plist will be examined.
 
-  def __init__ (self, autoBuild = True):
-    """
-    This class provides a sequence of network interfaces and their hardware
-    addresses. If a system has no nic installed, an 6-tuple will be generated
-    from random source. This generated address will have the unicast-/multicast
-    bit set.
+    On win32 systems the Windows Management Instrumentation will be queried.
 
-    @param autoBuild: if set to True a hardware-address will be generated if no
-        network interface card is installed.
+    If no interface could be detected at all, an interface will be generated
+    using the random number source. It will have the name 'generated'.
     """
 
-    self.interfaces  = self.__getInterfaces ()
-    self.hwaddresses = [self.getHWAddress (i) for i in self.interfaces]
+    # -------------------------------------------------------------------------
+    # Constructor
+    # -------------------------------------------------------------------------
 
-    self.firstMAC = None
+    def __init__(self):
 
-    for addr in self.hwaddresses:
-      if not self.__hwAddrIsEmpty (addr):
-        self.firstMAC = addr
-        break
+        trys = {'linux2': [self.__load_from_proc, self.__load_via_ifconf],
+                'darwin': [self.__load_from_plist],
+                'win32' : [self.__load_from_winmgmts]}
 
-    if autoBuild and self.firstMAC is None:
-      # Generated mac addresses have the unicast-/multicast-bit set !
-      self.firstMAC = getRandomBytes (6)
-      self.firstMAC [0] |= 0x80
+        nics = []
+        if sys.platform in trys:
+            for method in trys[sys.platform]:
+                nics = self.__strip_empty(method())
+                if nics:
+                    break
 
+        if not nics:
+            nics = [('generated', getRandomBytes(6))]
 
-  # ---------------------------------------------------------------------------
-  # Get the hardware address of an interface (MAC address)
-  # ---------------------------------------------------------------------------
+        self.nics = [(n, h, ("%02x:" * 6)[:-1] % tuple(h)) for (n, h) in nics]
 
-  def getHWAddress (self, interface):
-    """
-    This function returns the hardware address of an interface as sequence of
-    integers.
 
-    @param interface: network interface to fetch an address for. This is
-        usually an element from the interface-sequence.
 
-    @return: sequence of numbers with the hardware address
-    """
+    # -------------------------------------------------------------------------
+    # Load a list of interfaces from the proc-filesystem
+    # -------------------------------------------------------------------------
 
-    result = None
+    def __load_from_proc (self):
 
-    if sys.platform == 'linux2':
-      sfhd  = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
-      ifreq = (interface + '\0' * 32) [:32]
+        result = []
+        try:
+            nfhd = open('/proc/net/dev', 'r')
 
-      try:
-        data   = fcntl.ioctl (sfhd.fileno (), self.SIOCGIFHWADDR, ifreq)
-        result = array.array ('B', data [18:24]).tolist ()
+            try:
+                for line in [l.strip() for l in nfhd.readlines() if ':' in l]:
+                    result.append(line.split(':', 1)[0])
 
-      finally:
-        sfhd.close ()
+            finally:
+                nfhd.close()
 
-    elif sys.platform == 'win32':
-      parts  = interface.MACAddress.split (':')
-      args   = [16] * len (parts)
-      result = map (int, parts, args)
+            result = [(r, self.__hw_addr_from_socket(r)) for r in result]
 
-    return result
+        except:
+            pass
 
+        return result
 
-  # ---------------------------------------------------------------------------
-  # Get a string representation of a hardware address
-  # ---------------------------------------------------------------------------
 
-  def addrAsString (self, addr):
-    """
-    This function creates a string representation of a hardware address, where
-    all parts are separated by a colon.
+    # -------------------------------------------------------------------------
+    # Load a list of interfaces via IFCONF socket call
+    # -------------------------------------------------------------------------
 
-    @param addr: hardware address as a sequence of numbers
-    @return: string of the hardware address
-    """
+    def __load_via_ifconf(self):
 
-    return string.join (["%02X" % i for i in addr], ":")
+        SIOCGIFCONF = 0x8912
+        result = []
 
+        try:
+            sfhd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 
-  # ---------------------------------------------------------------------------
-  # Get a sequence of interfaces available to the system
-  # ---------------------------------------------------------------------------
+            try:
+                buffer = array.array('c', '\0' * 1024)
+                (addr, length) = buffer.buffer_info()
+                ifconf = struct.pack ("iP", length, addr)
+                data = fcntl.ioctl(sfhd.fileno(), SIOCGIFCONF, ifconf)
 
-  def __getInterfaces (self):
-    """
-    This function returns a sequence of network interfaces available to the
-    system. For POSIX systems this is a sequence of strings, and for NT-systems
-    this is a sequence of COM-Objects, representing the nics.
+                size, ptr = struct.unpack("iP", data)
+                for idx in range (0, size, 32):
+                    ifconf = buffer.tostring()[idx:idx+32]
+                    name = struct.unpack("16s16s", ifconf)[0].split('\0', 1)[0]
+                    result.append(name)
 
-    @return: sequence of network-interfaces
-    """
+            finally:
+                sfhd.close()
 
-    result = []
+            result = [(r, self.__hw_addr_from_socket(r)) for r in result]
 
-    if sys.platform == 'linux2':
-      try:
-        result = self.__getInterfacesFromProc ()
+        except:
+            pass
 
-      except:
-        try:
-          result = self.__getInterfacesFromSockets ()
+        return result
 
-        except:
-          pass
 
-    elif sys.platform == 'win32' and _HAS_GETOBJECT:
-      result = [i for i in GetObject ('winmgmts:').ExecQuery ("SELECT * FROM "
-                     "Win32_NetworkAdapterConfiguration WHERE IPEnabled=True")]
+    # -------------------------------------------------------------------------
+    # Get a hardware address for an interface using a socket
+    # -------------------------------------------------------------------------
 
-    return result
+    def __hw_addr_from_socket(self, iff):
 
+        SIOCGIFHWADDR = 0x8927
+        sfhd  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+        ifreq = (iff + '\0' * 32)[:32]
 
-  # ---------------------------------------------------------------------------
-  # Get a list of available network interfaces from /proc/net/dev
-  # ---------------------------------------------------------------------------
+        try:
+            data   = fcntl.ioctl(sfhd.fileno(), SIOCGIFHWADDR, ifreq)
+            result = array.array('B', data[18:24]).tolist()
 
-  def __getInterfacesFromProc (self):
+        finally:
+            sfhd.close()
 
-    result = []
-    nfhd   = open ('/proc/net/dev', 'r')
+        return result
 
-    try:
-      for line in [l.strip () for l in nfhd.readlines () if ':' in l]:
-        result.append (line.split (':', 1) [0])
 
-    finally:
-      nfhd.close ()
+    # -------------------------------------------------------------------------
+    # Get a list of interfaces using the windows management instrumentation
+    # -------------------------------------------------------------------------
 
-    return result
+    def __load_from_winmgmts(self):
 
+        result = []
+        try:
+            cmd = "SELECT * FROM Win32_NetworkAdapterConfiguration " \
+                  "WHERE IPEnabled=True"
+            for iff in [i for i in GetObject('winmgmts:').ExecQuery(cmd)]:
+                parts  = iff.MACAddress.split(':')
+                args   = [16] * len(parts)
+                result.append((iff.Caption, map(int, parts, args)))
 
-  # ---------------------------------------------------------------------------
-  # Get a list of network interfaces via sockets
-  # ---------------------------------------------------------------------------
+        except:
+            pass
 
-  def __getInterfacesFromSockets (self):
+        return result
 
-    result = []
-    sfhd   = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
 
-    try:
-      buffer = array.array ('c', '\0' * 1024)
-      (addr, length) = buffer.buffer_info ()
-      ifconf = struct.pack ("iP", length, addr)
-      data   = fcntl.ioctl (sfhd.fileno (), self.SIOCGIFCONF, ifconf)
+    # -------------------------------------------------------------------------
+    # Load the network information from the NetworkInterfaces.plist XML file
+    # -------------------------------------------------------------------------
 
-      size, ptr = struct.unpack ("iP", data)
-      for idx in range (0, size, 32):
-        ifconf = buffer.tostring () [idx:idx+32]
-        name = struct.unpack ("16s16s", ifconf) [0].split ('\0', 1) [0]
-        result.append (name)
+    def __load_from_plist(self):
 
-    finally:
-      sfhd.close ()
+        result = []
+        try:
+            import plistlib
+            path = "/Library/Preferences/SystemConfiguration/" \
+                   "NetworkInterfaces.plist"
 
-    return result
+            pl = plistlib.Plist.fromFile(path)
+            for iff in pl.Interfaces:
+                name = iff ['BSD Name']
+                hwaddr = [ord(c) for c in iff.IOMACAddress.data]
 
+                # FireWire devices seem to have longer hardware addresses which
+                # are theirfore not usable for UUID generation.
+                if len(hwaddr) == 6:
+                  result.append ((name, hwaddr))
 
-  # ---------------------------------------------------------------------------
-  # Check if a hardware address is NULL (all zeros)
-  # ---------------------------------------------------------------------------
+        except:
+            pass
 
-  def __hwAddrIsEmpty (self, address):
-    """
-    This function returns True, if a hardware address is all empty (zero). This
-    is the case for loopback-devices.
+        return result
 
-    @return: True for empty addresses, False otherwise
-    """
 
-    return address == [0] * len (address)
+    # -------------------------------------------------------------------------
+    # Throw away all entries having an 'empty' hardware address
+    # -------------------------------------------------------------------------
 
+    def __strip_empty (self, nics):
 
+        return [item for item in nics if sum (item[1])]
+
+
+
 # =============================================================================
 # This class implements an UUID generator
 # =============================================================================
@@ -316,213 +320,214 @@
 SHA1   = 5
 
 class Generator:
-  """
-  This class implements an UUID generator described in the internet draft at
-  'http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-05.txt' or also
-  described in the RPC-RFC.
-  """
+    """
+    This class implements an UUID generator described in the internet draft at
+    'http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-05.txt' or
+    also described in the RPC-RFC.
+    """
 
-  _NIC = NICInformation ()
+    _NIC = NetworkInterfaces ()
 
-  # ---------------------------------------------------------------------------
-  # Constructor
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Constructor
+    # -------------------------------------------------------------------------
 
-  def __init__ (self, version = TIME, namespace = None):
+    def __init__(self, version=TIME, namespace=None):
 
-    self.version      = version
-    self.__lastTime   = None
-    self.__clockSeq   = int ("%02x%02x" % tuple (getRandomBytes (2)), 16)
-    self.__clockField = self.__clockSeq & 0x3FFF | 0x8000
-    self.__namespace  = None
+        self.version = version
+        self.__lastTime = None
+        self.__clockSeq = int("%02x%02x" % tuple(getRandomBytes(2)), 16)
+        self.__clockField = self.__clockSeq & 0x3FFF | 0x8000
+        self.__namespace = None
 
-    if namespace is not None:
-      self.setNamespace (namespace)
+        if namespace is not None:
+            self.set_namespace(namespace)
 
-    self.__timeFormat = u"%016x%04x%s"
-    self.__randFormat = u"%02x" * 16
-    self.__hashFormat = u"%08x%04x%04x" + "%02x" * 8
-    self.__currNode   = "%02x" * 6 % tuple (self._NIC.firstMAC)
+        self.__timeFormat = u"%016x%04x%s"
+        self.__randFormat = u"%02x" * 16
+        self.__hashFormat = u"%08x%04x%04x" + "%02x" * 8
+        self.__currNode   = "%02x" * 6 % tuple(self._NIC.nics[0][1])
 
 
-  # ---------------------------------------------------------------------------
-  # Generate a new UUID
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Generate a new UUID
+    # -------------------------------------------------------------------------
 
-  def generate (self, version = None, namespace = None, name = None):
-    """
-    This function calls the appropriate method to generate a new UUID. If
-    you're about to create a lot of id's in a short time, you're better off
-    using the proper fucntion directly.
+    def generate(self, version=None, namespace=None, name=None):
+        """
+        This function calls the appropriate method to generate a new UUID. If
+        you're about to create a lot of id's in a short time, you're better off
+        using the proper fucntion directly.
 
-    @param version: if set generate an id of this version
-    @param namespace: if version is currently MD5 or SHA1 this parameter
-        defines the namespace to use. Alternatively one can use setNamespace ()
-    @param name: if version is MD5 or SHA1 this parameter specifies the name to
-        encode
+        @param version: if set generate an id of this version
+        @param namespace: if version is currently MD5 or SHA1 this parameter
+          defines the namespace to use. Alternatively one can use
+          set_namespace()
+        @param name: if version is MD5 or SHA1 this parameter specifies the
+          name to encode
 
-    @return: UUID as 32 character unicode string 
-    """
+        @return: UUID as 32 character unicode string 
+        """
 
-    vers = version or self.version
+        vers = version or self.version
 
-    if vers == TIME:
-      return self.generateTimeBased ()
+        if vers == TIME:
+            return self.generate_time_based()
 
-    elif vers == RANDOM:
-      return self.generateRandom ()
+        elif vers == RANDOM:
+            return self.generate_random()
 
-    elif vers == MD5:
-      return self.generateMD5 (name, namespace)
+        elif vers == MD5:
+            return self.generate_MD5(name, namespace)
 
-    elif vers == SHA1:
-      return self.generateSHA1 (name, namespace)
+        elif vers == SHA1:
+            return self.generate_SHA1(name, namespace)
 
-    else:
-      raise InvalidVersionError, version
+        else:
+            raise InvalidVersionError, version
 
 
-  # ---------------------------------------------------------------------------
-  # Generate a time-based UUID
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Generate a time-based UUID
+    # -------------------------------------------------------------------------
 
-  def generateTimeBased (self):
-    """
-    This function creates a time-based UUID
+    def generate_time_based(self):
+        """
+        Create a time-based UUID.
 
-    @return: UUID (as 32 character unicode string)
-    """
+        @return: UUID (as 32 character unicode string)
+        """
 
-    lock.acquire ()
+        lock.acquire()
 
-    timeStamp = long (time.time () * 10000000) + 122192928000000000L
-    if timeStamp != self.__lastTime:
-      self.__uuidsPerTick = 0
+        timeStamp = long(time.time() * 10000000) + 122192928000000000L
+        if timeStamp != self.__lastTime:
+          self.__uuidsPerTick = 0
 
-      # If the time has been set backward, we change the clock sequence
-      if timeStamp < self.__lastTime:
-        self.__clockSeq += 1
-        if self.__clockSeq > 0xFFFF:
-          self.__clockSeq = 0
+          # If the time has been set backward, we change the clock sequence
+          if timeStamp < self.__lastTime:
+            self.__clockSeq += 1
+            if self.__clockSeq > 0xFFFF:
+              self.__clockSeq = 0
 
-        self.__clockField = self.__clockSeq & 0x3FFF | 0x8000
+            self.__clockField = self.__clockSeq & 0x3FFF | 0x8000
 
-      self.__lastTime = timeStamp
+          self.__lastTime = timeStamp
 
-    else:
-      self.__uuidsPerTick += 1
-      timeStamp += self.__uuidsPerTick
+        else:
+          self.__uuidsPerTick += 1
+          timeStamp += self.__uuidsPerTick
 
-    lock.release ()
+        lock.release()
 
-    timeField = timeStamp & 0x0FFFFFFFFFFFFFFFF | 0x1000000000000000
+        timeField = timeStamp & 0x0FFFFFFFFFFFFFFFF | 0x1000000000000000
 
-    return self.__timeFormat % (timeField, self.__clockField, self.__currNode)
+        return self.__timeFormat % (timeField, self.__clockField,
+                                    self.__currNode)
 
 
-  # ---------------------------------------------------------------------------
-  # Generate an UUID from pseudo random numbers
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Generate an UUID from pseudo random numbers
+    # -------------------------------------------------------------------------
 
-  def generateRandom (self):
-    """
-    This function generates an UUID from pseudo random numbers
+    def generate_random(self):
+        """
+        This function generates an UUID from pseudo random numbers
 
-    @return: UUID (as 32 character unicode string)
-    """
+        @return: UUID (as 32 character unicode string)
+        """
 
-    data = getRandomBytes (16)
-    # Set the two most significant bits (bits 6, 7) of the
-    # clock_seq_hi_and_reserved to zero and one
-    data [8] = data [8] & 0x3F | 0x80
+        data = getRandomBytes(16)
+        # Set the two most significant bits (bits 6, 7) of the
+        # clock_seq_hi_and_reserved to zero and one
+        data[8] = data[8] & 0x3F | 0x80
 
-    # Multiplex the most significant bits of time_hi_and_version with 4
-    data [6] = data [6] | 0x40
+        # Multiplex the most significant bits of time_hi_and_version with 4
+        data[6] = data[6] | 0x40
 
-    return self.__randFormat % tuple (data)
+        return self.__randFormat % tuple(data)
 
 
-  # ---------------------------------------------------------------------------
-  # Generate a name-based UUID using an MD5 hash
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Generate a name-based UUID using an MD5 hash
+    # -------------------------------------------------------------------------
 
-  def generateMD5 (self, name, namespace = None):
-    """
-    This function generates a name based UUID using a MD5 hash.
+    def generate_MD5(self, name, namespace=None):
+        """
+        Generate a name based UUID using a MD5 hash.
 
-    @return: UUID (as 32 character unicode string)
-    """
+        @return: UUID (as 32 character unicode string)
+        """
     
-    if namespace is not None:
-      self.setNamespace (namespace)
+        if namespace is not None:
+            self.set_namespace(namespace)
 
-    if self.__namespace is None:
-      raise MissingNamespaceError
+        if self.__namespace is None:
+            raise MissingNamespaceError
 
-    digest = md5.new (self.__namespace)
-    if name is not None:
-      digest.update (name)
+        digest = md5.new(self.__namespace)
+        if name is not None:
+            digest.update(name)
 
-    return unicode (digest.hexdigest ())
+        return unicode(digest.hexdigest())
 
 
-  # ---------------------------------------------------------------------------
-  # Generate an UUID using a SHA1 hash
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Generate an UUID using a SHA1 hash
+    # -------------------------------------------------------------------------
 
-  def generateSHA1 (self, name, namespace = None):
-    """
-    This function generates a name based UUID using a SHA1 hash.
+    def generate_SHA1(self, name, namespace=None):
+        """
+        Generate a name based UUID using a SHA1 hash.
 
-    @return: UUID (as 32 character unicode string)
-    """
+        @return: UUID (as 32 character unicode string)
+        """
 
-    if namespace is not None:
-      self.setNamespace (namespace)
+        if namespace is not None:
+            self.set_namespace(namespace)
 
-    if self.__namespace is None:
-      raise MissingNamespaceError
+        if self.__namespace is None:
+            raise MissingNamespaceError
 
-    digest = sha.new (self.__namespace)
-    if name is not None:
-      digest.update (name)
+        digest = sha.new(self.__namespace)
+        if name is not None:
+            digest.update(name)
 
-    return unicode (digest.hexdigest () [:32])
+        return unicode(digest.hexdigest()[:32])
 
 
-  # ---------------------------------------------------------------------------
-  # Set the namespace to be used for name based UUIDs
-  # ---------------------------------------------------------------------------
+    # -------------------------------------------------------------------------
+    # Set the namespace to be used for name based UUIDs
+    # -------------------------------------------------------------------------
 
-  def setNamespace (self, newNS):
-    """
-    This function sets the namespace used for name based UUID generation
-    """
+    def set_namespace (self, newNS):
+        """
+        Set the namespace used for name based UUID generation.
+        """
 
-    if isinstance (newNS, types.StringType) or \
-        isinstance (newNS, types.UnicodeType):
+        if isinstance(newNS, basestring):
+            if len (newNS) == 36:
+                newNS = "".join(newNS.split('-'))
 
-      if len (newNS) == 36:
-        newNS = string.join (newNS.split ('-'), "")
+            elif len (newNS) != 32:
+                raise "Invalid namespace argument"
 
-      elif len (newNS) != 32:
-        raise "Invalid namespace argument"
+            parts = [newNS[:8], newNS[8:12], newNS[12:16], newNS[16:]]
 
-      parts = [newNS [:8], newNS [8:12], newNS [12:16], newNS [16:]]
+            timeLow = socket.htonl(long(parts[0], 16))
+            timeMid = socket.htons(int(parts[1], 16))
+            timeHi  = socket.htons(int(parts[2], 16))
+            rest    = [int(parts[3][i:i+2], 16) for i in range(0, 16, 2)]
 
-      timeLow = socket.htonl (long (parts [0], 16))
-      timeMid = socket.htons (int (parts [1], 16))
-      timeHi  = socket.htons (int (parts [2], 16))
-      rest    = [int (parts [3] [i:i+2], 16) for i in range (0, 16, 2)]
+            self.__namespace = struct.pack('>LHH8B', timeLow, timeMid, timeHi,
+                                           *rest)
 
-      self.__namespace = struct.pack ('>LHH8B', timeLow, timeMid, timeHi, 
*rest)
+        else:
+            raise InvalidNamespaceError(newNS)
 
-    else:
-      raise InvalidNamespaceError, newNS
 
-
 # Create a ready-to-use instance of the UUID generator
-UUID = Generator ()
+UUID = Generator()
 
 
 # =============================================================================
@@ -530,20 +535,20 @@
 # =============================================================================
 
 if __name__ == '__main__':
-  for i in range (5):
-    print "Time-Base:", repr (UUID.generateTimeBased ())
 
-  for i in range (5):
-    print "Random   :", repr (UUID.generateRandom ())
+    for i in range(5):
+        print "Time-Base:", repr(UUID.generate_time_based())
 
-  UUID.setNamespace ('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
-  print "Namespace: '6ba7b810-9dad-11d1-80b4-00c04fd430c8'"
-  print "Encoding : 'www.gnuenterprise.org'"
-  print "MD5      :", repr (UUID.generateMD5 ('www.gnuenterprise.org'))
-  print "SHA1     :", repr (UUID.generateSHA1 ('www.gnuenterprise.org'))
+    for i in range(5):
+        print "Random   :", repr(UUID.generate_random())
 
+    UUID.set_namespace('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
+    print "Namespace: '6ba7b810-9dad-11d1-80b4-00c04fd430c8'"
+    print "Encoding : 'www.gnuenterprise.org'"
+    print "MD5      :", repr(UUID.generate_MD5('www.gnuenterprise.org'))
+    print "SHA1     :", repr(UUID.generate_SHA1('www.gnuenterprise.org'))
 
-  print "T:", repr (UUID.generate (version = TIME))
-  print "R:", repr (UUID.generate (version = RANDOM))
-  print "M:", repr (UUID.generate (version = MD5, name = 'foobar'))
-  print "S:", repr (UUID.generate (version = SHA1, name = 'foobar'))
+    print "T:", repr(UUID.generate(version = TIME))
+    print "R:", repr(UUID.generate(version = RANDOM))
+    print "M:", repr(UUID.generate(version = MD5, name = 'foobar'))
+    print "S:", repr(UUID.generate(version = SHA1, name = 'foobar'))





reply via email to

[Prev in Thread] Current Thread [Next in Thread]