问题
I'm needing to both validate a list of UUID's as well as determine the version. For example, using https://www.beautifyconverter.com/uuid-validator.php and entering 25CCCA6F-1568-473E-BFED-EC08C31532C6 I can determine that it is both valid, and version 4. I see from https://www.snip2code.com/Snippet/12614/Validating-a-uuid4-with-Python- and How to determine if a string is a valid v4 UUID? that the UUID module can validate one at a time, or test for a particular version, but not sure if UUID will test for all 4 versions and return the version.
回答1:
Here is how I would iterative over a list of potential UUIDs and return a parallel list with either the version number (if valid) or None
otherwise.
Note especially that the UUID
constructor accepts UUID strings of any version. If the string is valid, you can query the .version
member to determine the version.
from uuid import UUID
def version_uuid(uuid):
try:
return UUID(uuid).version
except ValueError:
return None
def version_list(l):
return [version_uuid(uuid) for uuid in l]
if __name__=="__main__":
uuids = (
'0d14fbaa-8cd6-11e7-b2ed-28d244cd6e76',
'6fa459ea-ee8a-3ca4-894e-db77e160355e',
'16583cd3-8361-4fe6-a345-e1f546b86b74',
'886313e1-3b8a-5372-9b90-0c9aee199e5d',
'0d14fbaa-8cd6-11e7-b2ed-28d244cd6e7',
'6fa459ea-ee8a-3ca4-894e-db77e160355',
'16583cd3-8361-4fe6-a345-e1f546b86b7',
'886313e1-3b8a-5372-9b90-0c9aee199e5',
'481A8DE5-F0D1-E211-B425-E41F134196DA',
)
assert version_list(uuids) == [1,3,4,5,None,None,None,None,14]
回答2:
def validate_uuid4(uuid_string):
try:
val = UUID(uuid_string, version=4)
except ValueError:
# If it's a value error, then the string
# is not a valid hex code for a UUID.
return False
return True
You can use the above function to go through your list of uuid string and it will tell you whether a particular string in the list if a valid version 4 uuid
来源:https://stackoverflow.com/questions/45943754/how-to-validate-list-of-uuids-and-return-uuid-version