pythonuuidurn

Python UUID - Handle URN with namespace


Within input XMLs to process, I've got an URN UUID as fileIdentifier:

urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b

I need to check if this UUID is valid but the vendor:processor: part makes the standard module raising an error:

# same UUID in different flavors
x = "0269803d50c446b09f5060ef7fe3e22b"
y = "urn:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"
z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"

# testing different ways
uuid.UUID(x)
>>> UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b')  # yipee
uuid.UUID(y)
>>> UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b')  # yipee 2
uuid.UUID(z)
>>> Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\uuid.py", line 140, in __init__
        raise ValueError('badly formed hexadecimal UUID string')
      ValueError: badly formed hexadecimal UUID string

How to specify that vendor:processor: is part of UUID namespace (not sure that this term is correct)?

Env: Python 3.6.4 64 bits - Win10


Solution

  • Based on the manual, UUID URNs should be RFC4122 compliant. Now, from what I can tell the RFC does not support such "prefixes", thus I think you will have to parse that URN manually. Example code:

    import uuid
    
    # Returns a tuple (<uuid>, <prefix>)
    def urn_uuid_decode(urn_str):
        parts = urn_str.split(":")
    
        # Already supported format
        if len(parts) < 4:
            return uuid.UUID(urn_str), None
    
    
        return uuid.UUID("%s:%s:%s" % (parts[0], parts[-2], parts[-1])), ":".join(parts[1:-2])
    
    # same UUID in different flavors
    x = "0269803d50c446b09f5060ef7fe3e22b"
    y = "urn:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"
    z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b"
    
    print(urn_uuid_decode(x))
    print(urn_uuid_decode(y))
    print(urn_uuid_decode(z))
    

    Output:

    (UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), None)
    (UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), None)
    (UUID('0269803d-50c4-46b0-9f50-60ef7fe3e22b'), 'vendor:processor')
    

    Hope it helps