How to validate list of UUID's AND return UUID Version?

后端 未结 2 1762
一向
一向 2021-01-16 02:06

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 25CCCA

相关标签:
2条回答
  • 2021-01-16 02:30

    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]
    
    0 讨论(0)
  • 2021-01-16 02:30
    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

    0 讨论(0)
提交回复
热议问题