Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to convert a valid uuid from String to UUID?

Tags:

python

uuid

I receive the data as

   {         "name": "Unknown",         "parent": "Uncategorized",         "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16"     }, 

and I need to convert the uuid from String to uuid

I did not find a way on the python docs, or am I missing something basic here?

like image 574
daydreamer Avatar asked Apr 07 '13 05:04

daydreamer


People also ask

How do you generate a UUID from a string in Python?

uuid1() is defined in UUID library and helps to generate the random id using MAC address and time component. bytes : Returns id in form of 16 byte string. int : Returns id in form of 128-bit integer. hex : Returns random id as 32 character hexadecimal string.

What is uuid4 () in Python?

If all you want is a unique ID, you should probably call uuid1() or uuid4() . Note that uuid1() may compromise privacy since it creates a UUID containing the computer's network address. uuid4() creates a random UUID. Depending on support from the underlying platform, uuid1() may or may not return a “safe” UUID.

Is UUID thread safe python?

The thread-unsafe part of Python 2.5's uuid. uuid1() is when it compares the current current timestamp to the previous timestamp. Without a lock, two processes can end up comparing against the same globally saved timestamp.


2 Answers

Just pass it to uuid.UUID:

import uuid  o = {     "name": "Unknown",     "parent": "Uncategorized",     "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" }  print uuid.UUID(o['uuid']).hex 
like image 87
Blender Avatar answered Sep 20 '22 03:09

Blender


Don't call .hex on the UUID object unless you need the string representation of that uuid.

>>> import uuid >>> some_uuid = uuid.uuid4() >>> type(some_uuid) <class 'uuid.UUID'> >>> some_uuid_str = some_uuid.hex >>> some_uuid_str '5b77bdbade7b4fcb838f8111b68e18ae' >>> type(some_uuid_str) <class 'str'> 

Then as others mentioned above to convert a uuid string back to UUID instance do:

>>> uuid.UUID(some_uuid_str) UUID('5b77bdba-de7b-4fcb-838f-8111b68e18ae') >>> (some_uuid == uuid.UUID(some_uuid_str)) True >>> (some_uuid == some_uuid_str) False 

You could even set up a small helper utility function to validate the str and return the UUID back if you wanted to:

def is_valid_uuid(val):     try:         return uuid.UUID(str(val))     except ValueError:         return None 

Then to use it:

>>> some_uuid = uuid.uuid4() >>> is_valid_uuid(some_uuid) UUID('aa6635e1-e394-463b-b43d-69eb4c3a8570') >>> type(is_valid_uuid(some_uuid)) <class 'uuid.UUID'> 
like image 41
slajma Avatar answered Sep 23 '22 03:09

slajma