Coverage for api/validators.py : 51%

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
1import os
2import re
4from wtforms.validators import ValidationError
6# https://wtforms.readthedocs.io/en/2.3.x/validators/
9def get_module_path_if_exists(name):
11 root_path = os.getcwd()
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)
17 if folder == name:
18 return module_path
20 if os.path.exists(sub_module_path):
21 return sub_module_path
23 return None
26def is_alpha_num_underscore(name):
27 """returns whether the given name contains only alphanumeric or underscore
29 Parameters
30 ----------
31 name : str
32 to value to check for alphanumeric or underscore
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))
42def is_empty_str(string):
43 return string.strip() == ""
46def is_valid_slug(text):
47 # from validators package
48 slug_regex = re.compile(r"^[-a-zA-Z0-9_]+$")
49 return slug_regex.match(text)
52def 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
64def verify_slug(form, field):
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 )