Domanda

Come faccio a creare un GUID in Python che è indipendente dalla piattaforma? Ho sentito che c'è un metodo che utilizza ActivePython su Windows, ma è solo per Windows perché utilizza COM. Esiste un metodo che utilizza Python normale?

È stato utile?

Soluzione

  

Il modulo UUID, in Python 2.5 e fino, fornisce RFC UUID compliant   generazione. Vedere la documentazione del modulo e la RFC per i dettagli. [ fonte ]

Documenti:

Esempio (lavorando su 2 e 3):

>>> import uuid
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'

Altri suggerimenti

Se stai usando Python 2.5 o versione successiva, il modulo uuid è già incluso nella distribuzione standard di Python.

Esempio:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

Copiato da: https://docs.python.org/2/library/uuid.html (Dal momento che i link pubblicati non erano attivi e mantengono l'aggiornamento)

>>> 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')

Io uso GUID come chiavi casuali per operazioni del tipo di database.

La forma esadecimale, con i trattini e caratteri supplementari sembrano inutilmente lungo per me. Ma mi piace anche che le stringhe che rappresentano numeri esadecimali sono molto sicuri in quanto non contengono caratteri che possono causare problemi in alcune situazioni come '+', '=', etc ..

Invece di esadecimale, io uso una stringa base64 sicuro per le URL. Quanto segue non conforme a qualsiasi spec UUID / GUID se (tranne avere la quantità necessaria di casualità).

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('=', '')

Questa funzione è completamente configurabile e genera uid unico basato sul formato specificato

es: - [8, 4, 4, 4, 12], questo è il formato indicato e genererà il seguente 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

Se è necessario passare UUID per una chiave primaria per il modello o il campo univoco allora sotto il codice restituisce l'oggetto UUID -

 import uuid
 uuid.uuid4()

Se è necessario passare UUID come parametro per l'URL si può fare come sottostante Codice -

import uuid
str(uuid.uuid4())

Se si desidera che il valore esadecimale per un UUID si può fare il di sotto di un -

import uuid    
uuid.uuid4().hex
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top