Een GUID/UUID maken in Python

Hoe maak ik een GUID in Python die platformonafhankelijk is? Ik hoor dat er een methode is die ActivePython op Windows gebruikt, maar het is alleen Windows omdat het COM gebruikt. Is er een methode die gewone Python gebruikt?


Antwoord 1, autoriteit 100%

De uuid-modulebiedt onveranderlijke UUID-objecten (de UUID-klasse) en de functies uuid1(), uuid3(), uuid4(), uuid5() voor het genereren van versie 1, 3, 4 en 5 UUID’s zoals gespecificeerd in RFC 4122.

Als u alleen een unieke ID wilt, moet u waarschijnlijk uuid1() of uuid4() aanroepen. Houd er rekening mee dat uuid1() de privacy in gevaar kan brengen, omdat het een UUID maakt met het netwerkadres van de computer. uuid4() maakt een willekeurige UUID aan.

Documenten:

Voorbeelden (voor zowel Python 2 als 3):

>>> import uuid
>>> # make a random UUID
>>> uuid.uuid4()
UUID('bd65600d-8669-4903-8a14-af88203add38')
>>> # Convert a UUID to a string of hex digits in standard form
>>> str(uuid.uuid4())
'f50ec0b7-f960-400d-91f0-c42a6d44e3d0'
>>> # Convert a UUID to a 32-character hexadecimal string
>>> uuid.uuid4().hex
'9fe2c4e93f654fdbb24c02b15259716c'

Antwoord 2, autoriteit 33%

Als je Python 2.5 of hoger gebruikt, is de uuid-moduleis al inbegrepen bij de standaarddistributie van Python.

Bijvoorbeeld:

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

Antwoord 3, autoriteit 13%

Gekopieerd van: https://docs.python.org/3/library/ uuid.html(Omdat de geposte links niet actief waren en ze blijven updaten)

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

Antwoord 4, autoriteit 3%

Ik gebruik GUID’s als willekeurige sleutels voor bewerkingen van het databasetype.

De hexadecimale vorm, met de streepjes en extra tekens lijkt me onnodig lang. Maar ik vind het ook prettig dat strings die hexadecimale getallen vertegenwoordigen erg veilig zijn omdat ze geen tekens bevatten die in sommige situaties problemen kunnen veroorzaken, zoals ‘+’,’=’, enz..

In plaats van hexadecimaal gebruik ik een url-safe base64 string. Het volgende voldoet echter niet aan enige UUID/GUID-specificatie (behalve dat het de vereiste hoeveelheid willekeur heeft).

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

Antwoord 5

Als u UUID moet doorgeven voor een primaire sleutel voor uw model of uniek veld, retourneert onderstaande code het UUID-object –

import uuid
 uuid.uuid4()

Als u UUID als parameter voor URL moet doorgeven, kunt u dit doen zoals onderstaande code –

import uuid
str(uuid.uuid4())

Als je de hexadecimale waarde voor een UUID wilt, kun je de onderstaande doen –

import uuid    
uuid.uuid4().hex

Antwoord 6

Deze functie is volledig configureerbaar en genereert unieke uid op basis van het opgegeven formaat

eg:- [8, 4, 4, 4, 12] , dit is het formaat dat wordt genoemd en het zal de volgende uuid genereren

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

Antwoord 7

Antwoord 2019 (voor Windows):

Als je een permanente UUID wilt die een machine uniek identificeert op Windows, kun je deze truc gebruiken: (Gekopieerd van mijn antwoord op https ://stackoverflow.com/a/58416992/8874388).

from typing import Optional
import re
import subprocess
import uuid
def get_windows_uuid() -> Optional[uuid.UUID]:
    try:
        # Ask Windows for the device's permanent UUID. Throws if command missing/fails.
        txt = subprocess.check_output("wmic csproduct get uuid").decode()
        # Attempt to extract the UUID from the command's result.
        match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
        if match is not None:
            txt = match.group(1)
            if txt is not None:
                # Remove the surrounding whitespace (newlines, space, etc)
                # and useless dashes etc, by only keeping hex (0-9 A-F) chars.
                txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)
                # Ensure we have exactly 32 characters (16 bytes).
                if len(txt) == 32:
                    return uuid.UUID(txt)
    except:
        pass # Silence subprocess exception.
    return None
print(get_windows_uuid())

Gebruikt Windows API om de permanente UUID van de computer op te halen, verwerkt vervolgens de tekenreeks om er zeker van te zijn dat het een geldige UUID is en retourneert tenslotte een Python-object (https://docs.python.org/3/library/uuid.html) die u handige manieren geeft om de gegevens te gebruiken (zoals 128-bit integer, hexadecimale tekenreeks, enz.).

Veel succes!

PS: De subprocesaanroep kan waarschijnlijk worden vervangen door ctypes die rechtstreeks Windows-kernel/DLL’s aanroepen. Maar voor mijn doeleinden is deze functie alles wat ik nodig heb. Het doet een sterke validatie en levert correcte resultaten op.


Antwoord 8

Controleer ditbericht, heeft me veel geholpen. Kortom, de beste optie voor mij was:

import random 
import string 
# defining function for random 
# string id with parameter 
def ran_gen(size, chars=string.ascii_uppercase + string.digits): 
    return ''.join(random.choice(chars) for x in range(size)) 
# function call for random string 
# generation with size 8 and string  
print (ran_gen(8, "AEIOSUMA23")) 

Omdat ik slechts 4-6 willekeurige tekens nodig had in plaats van omvangrijke GUID.

Other episodes