How to create a GUID/UUID in Python

前端 未结 8 1033
情话喂你
情话喂你 2020-11-22 16:47

How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it\'s Windows only because it uses COM. Is there a

相关标签:
8条回答
  • 2020-11-22 17:36

    I use GUIDs as random keys for database type operations.

    The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..

    Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).

    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('=', '')
    
    0 讨论(0)
  • 2020-11-22 17:41

    Check this post, helped me a lot. In short, the best option for me 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")) 
    

    Because I needed just 4-6 random characters instead of bulky GUID.

    0 讨论(0)
提交回复
热议问题