1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
"""Input validation utilities"""
import re
import json
import base64
from typing import Any
def is_empty_string(value: str) -> bool:
"""Check whether as string is empty"""
return (isinstance(value, str) and value.strip() == "")
def is_empty_input(value: Any) -> bool:
"""Check whether user provided an empty value."""
return (value is None or is_empty_string(value))
def is_integer_input(value: Any) -> bool:
"""
Check whether user provided a value that can be parsed into an integer.
"""
def __is_int__(val, base):
try:
int(val, base=base)
except ValueError:
return False
return True
return isinstance(value, int) or (
(not is_empty_input(value)) and (
isinstance(value, str) and (
__is_int__(value, 10)
or __is_int__(value, 8)
or __is_int__(value, 16))))
def is_valid_representative_name(repr_name: str) -> bool:
"""
Check whether the given representative name is a valid according to our rules.
Parameters
----------
repr_name: a string of characters.
Checks For
----------
* The name MUST start with an alphabet [a-zA-Z]
* The name MUST end with an alphabet [a-zA-Z] or number [0-9]
* The name MUST be composed of alphabets [a-zA-Z], numbers [0-9],
underscores (_) and/or hyphens (-).
Returns
-------
Boolean indicating whether or not the name is valid.
"""
pattern = re.compile(r"^[a-zA-Z]+[a-zA-Z0-9_-]*[a-zA-Z0-9]$")
return bool(pattern.match(repr_name))
def encode_errors(errors: tuple[tuple[str, str], ...], form) -> str:
"""Encode form errors into base64 string."""
return base64.b64encode(
json.dumps({
"errors": dict(errors),
"original_formdata": dict(form)
}).encode("utf8"))
def decode_errors(errorstr) -> dict[str, dict]:
"""Decode errors from base64 string"""
if not bool(errorstr):
return {"errors": {}, "original_formdata": {}}
return json.loads(base64.b64decode(errorstr.encode("utf8")).decode("utf8"))
|