ยปCore Development>Code coverage>Lib/uuid.py

Python code coverage for Lib/uuid.py

#countcontent
1n/ar"""UUID objects (universally unique identifiers) according to RFC 4122.
2n/a
3n/aThis module provides immutable UUID objects (class UUID) and the functions
4n/auuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5
5n/aUUIDs as specified in RFC 4122.
6n/a
7n/aIf all you want is a unique ID, you should probably call uuid1() or uuid4().
8n/aNote that uuid1() may compromise privacy since it creates a UUID containing
9n/athe computer's network address. uuid4() creates a random UUID.
10n/a
11n/aTypical usage:
12n/a
13n/a >>> import uuid
14n/a
15n/a # make a UUID based on the host ID and current time
16n/a >>> uuid.uuid1() # doctest: +SKIP
17n/a UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
18n/a
19n/a # make a UUID using an MD5 hash of a namespace UUID and a name
20n/a >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
21n/a UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
22n/a
23n/a # make a random UUID
24n/a >>> uuid.uuid4() # doctest: +SKIP
25n/a UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
26n/a
27n/a # make a UUID using a SHA-1 hash of a namespace UUID and a name
28n/a >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
29n/a UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
30n/a
31n/a # make a UUID from a string of hex digits (braces and hyphens ignored)
32n/a >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
33n/a
34n/a # convert a UUID to a string of hex digits in standard form
35n/a >>> str(x)
36n/a '00010203-0405-0607-0809-0a0b0c0d0e0f'
37n/a
38n/a # get the raw 16 bytes of the UUID
39n/a >>> x.bytes
40n/a b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
41n/a
42n/a # make a UUID from a 16-byte string
43n/a >>> uuid.UUID(bytes=x.bytes)
44n/a UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
45n/a"""
46n/a
47n/aimport os
48n/a
49n/a__author__ = 'Ka-Ping Yee <ping@zesty.ca>'
50n/a
51n/aRESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
52n/a 'reserved for NCS compatibility', 'specified in RFC 4122',
53n/a 'reserved for Microsoft compatibility', 'reserved for future definition']
54n/a
55n/aint_ = int # The built-in int type
56n/abytes_ = bytes # The built-in bytes type
57n/a
58n/aclass UUID(object):
59n/a """Instances of the UUID class represent UUIDs as specified in RFC 4122.
60n/a UUID objects are immutable, hashable, and usable as dictionary keys.
61n/a Converting a UUID to a string with str() yields something in the form
62n/a '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts
63n/a five possible forms: a similar string of hexadecimal digits, or a tuple
64n/a of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
65n/a 48-bit values respectively) as an argument named 'fields', or a string
66n/a of 16 bytes (with all the integer fields in big-endian order) as an
67n/a argument named 'bytes', or a string of 16 bytes (with the first three
68n/a fields in little-endian order) as an argument named 'bytes_le', or a
69n/a single 128-bit integer as an argument named 'int'.
70n/a
71n/a UUIDs have these read-only attributes:
72n/a
73n/a bytes the UUID as a 16-byte string (containing the six
74n/a integer fields in big-endian byte order)
75n/a
76n/a bytes_le the UUID as a 16-byte string (with time_low, time_mid,
77n/a and time_hi_version in little-endian byte order)
78n/a
79n/a fields a tuple of the six integer fields of the UUID,
80n/a which are also available as six individual attributes
81n/a and two derived attributes:
82n/a
83n/a time_low the first 32 bits of the UUID
84n/a time_mid the next 16 bits of the UUID
85n/a time_hi_version the next 16 bits of the UUID
86n/a clock_seq_hi_variant the next 8 bits of the UUID
87n/a clock_seq_low the next 8 bits of the UUID
88n/a node the last 48 bits of the UUID
89n/a
90n/a time the 60-bit timestamp
91n/a clock_seq the 14-bit sequence number
92n/a
93n/a hex the UUID as a 32-character hexadecimal string
94n/a
95n/a int the UUID as a 128-bit integer
96n/a
97n/a urn the UUID as a URN as specified in RFC 4122
98n/a
99n/a variant the UUID variant (one of the constants RESERVED_NCS,
100n/a RFC_4122, RESERVED_MICROSOFT, or RESERVED_FUTURE)
101n/a
102n/a version the UUID version number (1 through 5, meaningful only
103n/a when the variant is RFC_4122)
104n/a """
105n/a
106n/a def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
107n/a int=None, version=None):
108n/a r"""Create a UUID from either a string of 32 hexadecimal digits,
109n/a a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
110n/a in little-endian order as the 'bytes_le' argument, a tuple of six
111n/a integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
112n/a 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
113n/a the 'fields' argument, or a single 128-bit integer as the 'int'
114n/a argument. When a string of hex digits is given, curly braces,
115n/a hyphens, and a URN prefix are all optional. For example, these
116n/a expressions all yield the same UUID:
117n/a
118n/a UUID('{12345678-1234-5678-1234-567812345678}')
119n/a UUID('12345678123456781234567812345678')
120n/a UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
121n/a UUID(bytes='\x12\x34\x56\x78'*4)
122n/a UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
123n/a '\x12\x34\x56\x78\x12\x34\x56\x78')
124n/a UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
125n/a UUID(int=0x12345678123456781234567812345678)
126n/a
127n/a Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
128n/a be given. The 'version' argument is optional; if given, the resulting
129n/a UUID will have its variant and version set according to RFC 4122,
130n/a overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
131n/a """
132n/a
133n/a if [hex, bytes, bytes_le, fields, int].count(None) != 4:
134n/a raise TypeError('one of the hex, bytes, bytes_le, fields, '
135n/a 'or int arguments must be given')
136n/a if hex is not None:
137n/a hex = hex.replace('urn:', '').replace('uuid:', '')
138n/a hex = hex.strip('{}').replace('-', '')
139n/a if len(hex) != 32:
140n/a raise ValueError('badly formed hexadecimal UUID string')
141n/a int = int_(hex, 16)
142n/a if bytes_le is not None:
143n/a if len(bytes_le) != 16:
144n/a raise ValueError('bytes_le is not a 16-char string')
145n/a bytes = (bytes_le[4-1::-1] + bytes_le[6-1:4-1:-1] +
146n/a bytes_le[8-1:6-1:-1] + bytes_le[8:])
147n/a if bytes is not None:
148n/a if len(bytes) != 16:
149n/a raise ValueError('bytes is not a 16-char string')
150n/a assert isinstance(bytes, bytes_), repr(bytes)
151n/a int = int_.from_bytes(bytes, byteorder='big')
152n/a if fields is not None:
153n/a if len(fields) != 6:
154n/a raise ValueError('fields is not a 6-tuple')
155n/a (time_low, time_mid, time_hi_version,
156n/a clock_seq_hi_variant, clock_seq_low, node) = fields
157n/a if not 0 <= time_low < 1<<32:
158n/a raise ValueError('field 1 out of range (need a 32-bit value)')
159n/a if not 0 <= time_mid < 1<<16:
160n/a raise ValueError('field 2 out of range (need a 16-bit value)')
161n/a if not 0 <= time_hi_version < 1<<16:
162n/a raise ValueError('field 3 out of range (need a 16-bit value)')
163n/a if not 0 <= clock_seq_hi_variant < 1<<8:
164n/a raise ValueError('field 4 out of range (need an 8-bit value)')
165n/a if not 0 <= clock_seq_low < 1<<8:
166n/a raise ValueError('field 5 out of range (need an 8-bit value)')
167n/a if not 0 <= node < 1<<48:
168n/a raise ValueError('field 6 out of range (need a 48-bit value)')
169n/a clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
170n/a int = ((time_low << 96) | (time_mid << 80) |
171n/a (time_hi_version << 64) | (clock_seq << 48) | node)
172n/a if int is not None:
173n/a if not 0 <= int < 1<<128:
174n/a raise ValueError('int is out of range (need a 128-bit value)')
175n/a if version is not None:
176n/a if not 1 <= version <= 5:
177n/a raise ValueError('illegal version number')
178n/a # Set the variant to RFC 4122.
179n/a int &= ~(0xc000 << 48)
180n/a int |= 0x8000 << 48
181n/a # Set the version number.
182n/a int &= ~(0xf000 << 64)
183n/a int |= version << 76
184n/a self.__dict__['int'] = int
185n/a
186n/a def __eq__(self, other):
187n/a if isinstance(other, UUID):
188n/a return self.int == other.int
189n/a return NotImplemented
190n/a
191n/a # Q. What's the value of being able to sort UUIDs?
192n/a # A. Use them as keys in a B-Tree or similar mapping.
193n/a
194n/a def __lt__(self, other):
195n/a if isinstance(other, UUID):
196n/a return self.int < other.int
197n/a return NotImplemented
198n/a
199n/a def __gt__(self, other):
200n/a if isinstance(other, UUID):
201n/a return self.int > other.int
202n/a return NotImplemented
203n/a
204n/a def __le__(self, other):
205n/a if isinstance(other, UUID):
206n/a return self.int <= other.int
207n/a return NotImplemented
208n/a
209n/a def __ge__(self, other):
210n/a if isinstance(other, UUID):
211n/a return self.int >= other.int
212n/a return NotImplemented
213n/a
214n/a def __hash__(self):
215n/a return hash(self.int)
216n/a
217n/a def __int__(self):
218n/a return self.int
219n/a
220n/a def __repr__(self):
221n/a return '%s(%r)' % (self.__class__.__name__, str(self))
222n/a
223n/a def __setattr__(self, name, value):
224n/a raise TypeError('UUID objects are immutable')
225n/a
226n/a def __str__(self):
227n/a hex = '%032x' % self.int
228n/a return '%s-%s-%s-%s-%s' % (
229n/a hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
230n/a
231n/a @property
232n/a def bytes(self):
233n/a return self.int.to_bytes(16, 'big')
234n/a
235n/a @property
236n/a def bytes_le(self):
237n/a bytes = self.bytes
238n/a return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] +
239n/a bytes[8:])
240n/a
241n/a @property
242n/a def fields(self):
243n/a return (self.time_low, self.time_mid, self.time_hi_version,
244n/a self.clock_seq_hi_variant, self.clock_seq_low, self.node)
245n/a
246n/a @property
247n/a def time_low(self):
248n/a return self.int >> 96
249n/a
250n/a @property
251n/a def time_mid(self):
252n/a return (self.int >> 80) & 0xffff
253n/a
254n/a @property
255n/a def time_hi_version(self):
256n/a return (self.int >> 64) & 0xffff
257n/a
258n/a @property
259n/a def clock_seq_hi_variant(self):
260n/a return (self.int >> 56) & 0xff
261n/a
262n/a @property
263n/a def clock_seq_low(self):
264n/a return (self.int >> 48) & 0xff
265n/a
266n/a @property
267n/a def time(self):
268n/a return (((self.time_hi_version & 0x0fff) << 48) |
269n/a (self.time_mid << 32) | self.time_low)
270n/a
271n/a @property
272n/a def clock_seq(self):
273n/a return (((self.clock_seq_hi_variant & 0x3f) << 8) |
274n/a self.clock_seq_low)
275n/a
276n/a @property
277n/a def node(self):
278n/a return self.int & 0xffffffffffff
279n/a
280n/a @property
281n/a def hex(self):
282n/a return '%032x' % self.int
283n/a
284n/a @property
285n/a def urn(self):
286n/a return 'urn:uuid:' + str(self)
287n/a
288n/a @property
289n/a def variant(self):
290n/a if not self.int & (0x8000 << 48):
291n/a return RESERVED_NCS
292n/a elif not self.int & (0x4000 << 48):
293n/a return RFC_4122
294n/a elif not self.int & (0x2000 << 48):
295n/a return RESERVED_MICROSOFT
296n/a else:
297n/a return RESERVED_FUTURE
298n/a
299n/a @property
300n/a def version(self):
301n/a # The version bits are only meaningful for RFC 4122 UUIDs.
302n/a if self.variant == RFC_4122:
303n/a return int((self.int >> 76) & 0xf)
304n/a
305n/adef _popen(command, *args):
306n/a import os, shutil, subprocess
307n/a executable = shutil.which(command)
308n/a if executable is None:
309n/a path = os.pathsep.join(('/sbin', '/usr/sbin'))
310n/a executable = shutil.which(command, path=path)
311n/a if executable is None:
312n/a return None
313n/a # LC_ALL=C to ensure English output, stderr=DEVNULL to prevent output
314n/a # on stderr (Note: we don't have an example where the words we search
315n/a # for are actually localized, but in theory some system could do so.)
316n/a env = dict(os.environ)
317n/a env['LC_ALL'] = 'C'
318n/a proc = subprocess.Popen((executable,) + args,
319n/a stdout=subprocess.PIPE,
320n/a stderr=subprocess.DEVNULL,
321n/a env=env)
322n/a return proc
323n/a
324n/adef _find_mac(command, args, hw_identifiers, get_index):
325n/a try:
326n/a proc = _popen(command, *args.split())
327n/a if not proc:
328n/a return
329n/a with proc:
330n/a for line in proc.stdout:
331n/a words = line.lower().rstrip().split()
332n/a for i in range(len(words)):
333n/a if words[i] in hw_identifiers:
334n/a try:
335n/a word = words[get_index(i)]
336n/a mac = int(word.replace(b':', b''), 16)
337n/a if mac:
338n/a return mac
339n/a except (ValueError, IndexError):
340n/a # Virtual interfaces, such as those provided by
341n/a # VPNs, do not have a colon-delimited MAC address
342n/a # as expected, but a 16-byte HWAddr separated by
343n/a # dashes. These should be ignored in favor of a
344n/a # real MAC address
345n/a pass
346n/a except OSError:
347n/a pass
348n/a
349n/adef _ifconfig_getnode():
350n/a """Get the hardware address on Unix by running ifconfig."""
351n/a # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
352n/a for args in ('', '-a', '-av'):
353n/a mac = _find_mac('ifconfig', args, [b'hwaddr', b'ether'], lambda i: i+1)
354n/a if mac:
355n/a return mac
356n/a
357n/adef _ip_getnode():
358n/a """Get the hardware address on Unix by running ip."""
359n/a # This works on Linux with iproute2.
360n/a mac = _find_mac('ip', 'link list', [b'link/ether'], lambda i: i+1)
361n/a if mac:
362n/a return mac
363n/a
364n/adef _arp_getnode():
365n/a """Get the hardware address on Unix by running arp."""
366n/a import os, socket
367n/a try:
368n/a ip_addr = socket.gethostbyname(socket.gethostname())
369n/a except OSError:
370n/a return None
371n/a
372n/a # Try getting the MAC addr from arp based on our IP address (Solaris).
373n/a return _find_mac('arp', '-an', [os.fsencode(ip_addr)], lambda i: -1)
374n/a
375n/adef _lanscan_getnode():
376n/a """Get the hardware address on Unix by running lanscan."""
377n/a # This might work on HP-UX.
378n/a return _find_mac('lanscan', '-ai', [b'lan0'], lambda i: 0)
379n/a
380n/adef _netstat_getnode():
381n/a """Get the hardware address on Unix by running netstat."""
382n/a # This might work on AIX, Tru64 UNIX and presumably on IRIX.
383n/a try:
384n/a proc = _popen('netstat', '-ia')
385n/a if not proc:
386n/a return
387n/a with proc:
388n/a words = proc.stdout.readline().rstrip().split()
389n/a try:
390n/a i = words.index(b'Address')
391n/a except ValueError:
392n/a return
393n/a for line in proc.stdout:
394n/a try:
395n/a words = line.rstrip().split()
396n/a word = words[i]
397n/a if len(word) == 17 and word.count(b':') == 5:
398n/a mac = int(word.replace(b':', b''), 16)
399n/a if mac:
400n/a return mac
401n/a except (ValueError, IndexError):
402n/a pass
403n/a except OSError:
404n/a pass
405n/a
406n/adef _ipconfig_getnode():
407n/a """Get the hardware address on Windows by running ipconfig.exe."""
408n/a import os, re
409n/a dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
410n/a try:
411n/a import ctypes
412n/a buffer = ctypes.create_string_buffer(300)
413n/a ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
414n/a dirs.insert(0, buffer.value.decode('mbcs'))
415n/a except:
416n/a pass
417n/a for dir in dirs:
418n/a try:
419n/a pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
420n/a except OSError:
421n/a continue
422n/a with pipe:
423n/a for line in pipe:
424n/a value = line.split(':')[-1].strip().lower()
425n/a if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
426n/a return int(value.replace('-', ''), 16)
427n/a
428n/adef _netbios_getnode():
429n/a """Get the hardware address on Windows using NetBIOS calls.
430n/a See http://support.microsoft.com/kb/118623 for details."""
431n/a import win32wnet, netbios
432n/a ncb = netbios.NCB()
433n/a ncb.Command = netbios.NCBENUM
434n/a ncb.Buffer = adapters = netbios.LANA_ENUM()
435n/a adapters._pack()
436n/a if win32wnet.Netbios(ncb) != 0:
437n/a return
438n/a adapters._unpack()
439n/a for i in range(adapters.length):
440n/a ncb.Reset()
441n/a ncb.Command = netbios.NCBRESET
442n/a ncb.Lana_num = ord(adapters.lana[i])
443n/a if win32wnet.Netbios(ncb) != 0:
444n/a continue
445n/a ncb.Reset()
446n/a ncb.Command = netbios.NCBASTAT
447n/a ncb.Lana_num = ord(adapters.lana[i])
448n/a ncb.Callname = '*'.ljust(16)
449n/a ncb.Buffer = status = netbios.ADAPTER_STATUS()
450n/a if win32wnet.Netbios(ncb) != 0:
451n/a continue
452n/a status._unpack()
453n/a bytes = status.adapter_address[:6]
454n/a if len(bytes) != 6:
455n/a continue
456n/a return int.from_bytes(bytes, 'big')
457n/a
458n/a# Thanks to Thomas Heller for ctypes and for his help with its use here.
459n/a
460n/a# If ctypes is available, use it to find system routines for UUID generation.
461n/a# XXX This makes the module non-thread-safe!
462n/a_uuid_generate_time = _UuidCreate = None
463n/atry:
464n/a import ctypes, ctypes.util
465n/a import sys
466n/a
467n/a # The uuid_generate_* routines are provided by libuuid on at least
468n/a # Linux and FreeBSD, and provided by libc on Mac OS X.
469n/a _libnames = ['uuid']
470n/a if not sys.platform.startswith('win'):
471n/a _libnames.append('c')
472n/a for libname in _libnames:
473n/a try:
474n/a lib = ctypes.CDLL(ctypes.util.find_library(libname))
475n/a except Exception:
476n/a continue
477n/a if hasattr(lib, 'uuid_generate_time'):
478n/a _uuid_generate_time = lib.uuid_generate_time
479n/a break
480n/a del _libnames
481n/a
482n/a # The uuid_generate_* functions are broken on MacOS X 10.5, as noted
483n/a # in issue #8621 the function generates the same sequence of values
484n/a # in the parent process and all children created using fork (unless
485n/a # those children use exec as well).
486n/a #
487n/a # Assume that the uuid_generate functions are broken from 10.5 onward,
488n/a # the test can be adjusted when a later version is fixed.
489n/a if sys.platform == 'darwin':
490n/a if int(os.uname().release.split('.')[0]) >= 9:
491n/a _uuid_generate_time = None
492n/a
493n/a # On Windows prior to 2000, UuidCreate gives a UUID containing the
494n/a # hardware address. On Windows 2000 and later, UuidCreate makes a
495n/a # random UUID and UuidCreateSequential gives a UUID containing the
496n/a # hardware address. These routines are provided by the RPC runtime.
497n/a # NOTE: at least on Tim's WinXP Pro SP2 desktop box, while the last
498n/a # 6 bytes returned by UuidCreateSequential are fixed, they don't appear
499n/a # to bear any relationship to the MAC address of any network device
500n/a # on the box.
501n/a try:
502n/a lib = ctypes.windll.rpcrt4
503n/a except:
504n/a lib = None
505n/a _UuidCreate = getattr(lib, 'UuidCreateSequential',
506n/a getattr(lib, 'UuidCreate', None))
507n/aexcept:
508n/a pass
509n/a
510n/adef _unixdll_getnode():
511n/a """Get the hardware address on Unix using ctypes."""
512n/a _buffer = ctypes.create_string_buffer(16)
513n/a _uuid_generate_time(_buffer)
514n/a return UUID(bytes=bytes_(_buffer.raw)).node
515n/a
516n/adef _windll_getnode():
517n/a """Get the hardware address on Windows using ctypes."""
518n/a _buffer = ctypes.create_string_buffer(16)
519n/a if _UuidCreate(_buffer) == 0:
520n/a return UUID(bytes=bytes_(_buffer.raw)).node
521n/a
522n/adef _random_getnode():
523n/a """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
524n/a import random
525n/a return random.getrandbits(48) | 0x010000000000
526n/a
527n/a_node = None
528n/a
529n/adef getnode():
530n/a """Get the hardware address as a 48-bit positive integer.
531n/a
532n/a The first time this runs, it may launch a separate program, which could
533n/a be quite slow. If all attempts to obtain the hardware address fail, we
534n/a choose a random 48-bit number with its eighth bit set to 1 as recommended
535n/a in RFC 4122.
536n/a """
537n/a
538n/a global _node
539n/a if _node is not None:
540n/a return _node
541n/a
542n/a import sys
543n/a if sys.platform == 'win32':
544n/a getters = [_windll_getnode, _netbios_getnode, _ipconfig_getnode]
545n/a else:
546n/a getters = [_unixdll_getnode, _ifconfig_getnode, _ip_getnode,
547n/a _arp_getnode, _lanscan_getnode, _netstat_getnode]
548n/a
549n/a for getter in getters + [_random_getnode]:
550n/a try:
551n/a _node = getter()
552n/a except:
553n/a continue
554n/a if _node is not None:
555n/a return _node
556n/a
557n/a_last_timestamp = None
558n/a
559n/adef uuid1(node=None, clock_seq=None):
560n/a """Generate a UUID from a host ID, sequence number, and the current time.
561n/a If 'node' is not given, getnode() is used to obtain the hardware
562n/a address. If 'clock_seq' is given, it is used as the sequence number;
563n/a otherwise a random 14-bit sequence number is chosen."""
564n/a
565n/a # When the system provides a version-1 UUID generator, use it (but don't
566n/a # use UuidCreate here because its UUIDs don't conform to RFC 4122).
567n/a if _uuid_generate_time and node is clock_seq is None:
568n/a _buffer = ctypes.create_string_buffer(16)
569n/a _uuid_generate_time(_buffer)
570n/a return UUID(bytes=bytes_(_buffer.raw))
571n/a
572n/a global _last_timestamp
573n/a import time
574n/a nanoseconds = int(time.time() * 1e9)
575n/a # 0x01b21dd213814000 is the number of 100-ns intervals between the
576n/a # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
577n/a timestamp = int(nanoseconds/100) + 0x01b21dd213814000
578n/a if _last_timestamp is not None and timestamp <= _last_timestamp:
579n/a timestamp = _last_timestamp + 1
580n/a _last_timestamp = timestamp
581n/a if clock_seq is None:
582n/a import random
583n/a clock_seq = random.getrandbits(14) # instead of stable storage
584n/a time_low = timestamp & 0xffffffff
585n/a time_mid = (timestamp >> 32) & 0xffff
586n/a time_hi_version = (timestamp >> 48) & 0x0fff
587n/a clock_seq_low = clock_seq & 0xff
588n/a clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
589n/a if node is None:
590n/a node = getnode()
591n/a return UUID(fields=(time_low, time_mid, time_hi_version,
592n/a clock_seq_hi_variant, clock_seq_low, node), version=1)
593n/a
594n/adef uuid3(namespace, name):
595n/a """Generate a UUID from the MD5 hash of a namespace UUID and a name."""
596n/a from hashlib import md5
597n/a hash = md5(namespace.bytes + bytes(name, "utf-8")).digest()
598n/a return UUID(bytes=hash[:16], version=3)
599n/a
600n/adef uuid4():
601n/a """Generate a random UUID."""
602n/a return UUID(bytes=os.urandom(16), version=4)
603n/a
604n/adef uuid5(namespace, name):
605n/a """Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
606n/a from hashlib import sha1
607n/a hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
608n/a return UUID(bytes=hash[:16], version=5)
609n/a
610n/a# The following standard UUIDs are for use with uuid3() or uuid5().
611n/a
612n/aNAMESPACE_DNS = UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')
613n/aNAMESPACE_URL = UUID('6ba7b811-9dad-11d1-80b4-00c04fd430c8')
614n/aNAMESPACE_OID = UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
615n/aNAMESPACE_X500 = UUID('6ba7b814-9dad-11d1-80b4-00c04fd430c8')