Jak utworzyć GUID/UUID w Pythonie

Jak utworzyć GUID w Pythonie, który jest niezależny od platformy? Słyszałem, że jest metoda wykorzystująca ActivePython na Windowsie, ale to Windows tylko dlatego, że używa COM. Czy istnieje metoda wykorzystująca zwykły Python?

Author: dreftymac, 2009-02-11

5 answers

Moduł uuid, w Pythonie 2.5 i nowszym, zapewnia uuid zgodny z RFC generacji. Szczegółowe informacje można znaleźć w dokumentacji modułu i RFC. [source ]

Docs:

Przykład (działa na 2 i 3):

>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'
 450
Author: stuartd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-31 14:09:49

Jeśli używasz Pythona 2.5 lub nowszego, moduł uuid jest już dołączona do standardowej dystrybucji Pythona.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
 302
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-17 08:50:02

Skopiowane z: https://docs.python.org/2/library/uuid.html (ponieważ zamieszczone linki nie były aktywne i ciągle się aktualizują)

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
 92
Author: Balaji Boggaram Ramanarayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-04 19:46:25

Używam GUID jako losowych kluczy do operacji typu bazy danych.

Forma szesnastkowa, z myślnikami i dodatkowymi znakami wydaje mi się niepotrzebnie długa. Ale podoba mi się również to, że łańcuchy liczb szesnastkowych są bardzo bezpieczne, ponieważ nie zawierają znaków, które mogą powodować problemy w niektórych sytuacjach, takich jak'+','=', itp..

Zamiast szesnastkowego, używam bezpiecznego dla url-u łańcucha base64. Poniższe nie są zgodne z żadną specyfikacją UUID/GUID (poza wymagana ilość losowości).

import base64
import uuid

# get a UUID - URL safe, Base64
def get_a_uuid():
    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
    return r_uuid.replace('=', '')
 26
Author: Chris Dutrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-18 19:20:48

Ta funkcja jest w pełni konfigurowalna i generuje unikalny uid na podstawie formatu określonego

Eg:- [8, 4, 4, 4, 12] , jest to wspomniany format i wygeneruje on następujący uuid

LxoYNyXe-7hbQ-caJt-Dsdu-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string
 2
Author: Manoj Selvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-25 04:51:36