Python UUID - 使用命名空间处理URN

时间:2018-03-20 10:07:19

标签: python uuid urn

在要处理的输入XML中,我有一个URN UUID作为fileIdentifier:

vendor:processor:

我需要检查此UUID是否有效,但# 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 部分使标准模块引发错误:

vendor:processor:

如何指定cfg.CreateMap<int?, PropertyModel<int?>>().ConvertUsing<ValueToPropertyModelConverter<int?>>(); cfg.CreateMap<double?, PropertyModel<double?>>().ConvertUsing<ValueToPropertyModelConverter<double?>>(); cfg.CreateMap<string, PropertyModel<string>>().ConvertUsing<ValueToPropertyModelConverter<string>>(); 是UUID名称空间的一部分(不确定这个术语是否正确)?

环境:Python 3.6.4 64位 - Win10

1 个答案:

答案 0 :(得分:1)

根据手册,UUID URN应符合RFC4122标准。现在,据我所知,RFC不支持这样的“前缀”,因此我认为你必须手动解析该URN。示例代码:

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

输出:

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

希望有所帮助