# Coverage for api/validators.py : 51%

## 31 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import os

2 import re

3

4 from wtforms.validators import ValidationError

5

6# https://wtforms.readthedocs.io/en/2.3.x/validators/

7

8

9 def get_module_path_if_exists(name):

10

11 root_path = os.getcwd()

12

13 for folder in os.listdir(os.path.join(root_path, "modules")):

14 module_path = os.path.join(root_path, "modules", folder)

15 sub_module_path = os.path.join(module_path, name)

16

17 if folder == name:

18 return module_path

19

20 if os.path.exists(sub_module_path):

21 return sub_module_path

22

23 return None

24

25

26 def is_alpha_num_underscore(name):

27 """returns whether the given name contains only alphanumeric or underscore

28

29 Parameters

30 ----------

31 name : str

32 to value to check for alphanumeric or underscore

33

34 Returns

35 -------

36 bool

37 returns ``True`` if ``name`` is alphanumeric, ``False`` otherwise

38 """

39 return bool(re.match(r"^[A-Za-z0-9_]+$", name))

40

41

42 def is_empty_str(string):

43 return string.strip() == ""

44

45

46 def is_valid_slug(text):

47 # from validators package

48 slug_regex = re.compile(r"^[-a-zA-Z0-9_]+$")

49 return slug_regex.match(text)

50

51

52 def is_valid_url(url):

53 protocol = r"^((?:http|ftp)s?://)?"

54 domain = r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|localhost)"

55 ipv4 = r"(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}"

56 ipv6 = r"([a-f0-9:]+:+)+[a-f0-9]+"

57 port = r"(?::\d+)?(?:/?|[/?]\S+)$"

58 url_regex = re.compile(

59 protocol + domain + "|" + ipv4 + "|" + ipv6 + port, re.IGNORECASE

60 )

61 return url_regex.match(url) is not None

62

63

64 def verify_slug(form, field):

65

66 if not is_valid_slug(field.data):

67 raise ValidationError(

68 "Slugs can only contain alphabets, numbers and hyphens (-). eg. good-day-1"

69 )