How to create a GUID/UUID in Python

前端 未结 8 1090
情话喂你
情话喂你 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('=', '')
    

提交回复
热议问题