Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/validators/uuid.py: 93%

14 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:08 +0000

1"""UUID.""" 

2# -*- coding: utf-8 -*- 

3 

4# standard 

5from typing import Union 

6from uuid import UUID 

7import re 

8 

9# local 

10from .utils import validator 

11 

12 

13@validator 

14def uuid(value: Union[str, UUID], /): 

15 """Return whether or not given value is a valid UUID-v4 string. 

16 

17 This validator is based on [WTForms UUID validator][1]. 

18 

19 [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539 

20 

21 Examples: 

22 >>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8') 

23 # Output: True 

24 >>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8') 

25 # Output: ValidationFailure(func=uuid, ...) 

26 

27 Args: 

28 value: 

29 UUID string or object to validate. 

30 

31 Returns: 

32 (Literal[True]): 

33 If `value` is a valid UUID. 

34 (ValidationFailure): 

35 If `value` is an invalid UUID. 

36 

37 > *New in version 0.2.0*. 

38 """ 

39 if not value: 

40 return False 

41 if isinstance(value, UUID): 

42 return True 

43 try: 

44 return UUID(value) or re.match( 

45 r"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$", value 

46 ) 

47 except ValueError: 

48 return False