Programing

Python에서 GUID / UUID를 만드는 방법

lottogame 2020. 10. 3. 09:46
반응형

Python에서 GUID / UUID를 만드는 방법


플랫폼 독립적 인 Python에서 GUID를 어떻게 생성합니까? Windows에서 ActivePython을 사용하는 방법이 있다고 들었지만 COM을 사용하기 때문에 Windows입니다. 일반 Python을 사용하는 방법이 있습니까?


Python 2.5 이상에서 uuid 모듈은 RFC 준수 UUID 생성을 제공합니다. 자세한 내용은 모듈 문서 및 RFC를 참조하십시오. [ 출처 ]

문서 :

예 (2 및 3 작업) :

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

Python 2.5 이상을 사용하는 경우 uuid 모듈 이 이미 Python 표준 배포에 포함되어 있습니다.

전의:

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

복사 : https://docs.python.org/2/library/uuid.html (게시 된 링크가 활성화되지 않았고 계속 업데이트되었으므로)

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

GUID를 데이터베이스 유형 작업을위한 임의의 키로 사용합니다.

대시와 추가 문자가있는 16 진수 형식은 불필요하게 길어 보입니다. 그러나 16 진수를 나타내는 문자열은 '+', '='등과 같은 일부 상황에서 문제를 일으킬 수있는 문자를 포함하지 않는다는 점에서 매우 안전하다는 점도 마음에 듭니다.

16 진수 대신 url-safe base64 문자열을 사용합니다. 다음은 UUID / GUID 사양을 준수하지 않습니다 (필요한 무작위성 제외).

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

모델 또는 고유 필드의 기본 키에 대한 UUID를 전달해야하는 경우 아래 코드는 UUID 개체를 반환합니다.

 import uuid
 uuid.uuid4()

URL의 매개 변수로 UUID를 전달해야하는 경우 아래 코드와 같이 할 수 있습니다.

import uuid
str(uuid.uuid4())

UUID의 16 진수 값을 원하면 다음을 수행 할 수 있습니다.

import uuid    
uuid.uuid4().hex

이 기능은 완전히 구성 가능하며 지정된 형식에 따라 고유 한 uid를 생성합니다.

예 :-[8, 4, 4, 4, 12], 이것은 언급 된 형식이며 다음 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

참고 URL : https://stackoverflow.com/questions/534839/how-to-create-a-guid-uuid-in-python

반응형