Skip to content

Commit d8f5d7d

Browse files
committed
Program rewrite to allow all python versions
1 parent fdd094d commit d8f5d7d

File tree

7 files changed

+295
-260
lines changed

7 files changed

+295
-260
lines changed

README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
## Install
55
* Pip: Install with `pip install flask_parameter_validation`.
66
* Manually:
7-
- `git clone https://github.com/Ge0rg3/Flask-Parameter-Validation.git`
7+
- `git clone https://github.com/Ge0rg3/flask-parameter-validation.git`
88
- `python setup.py install`
99

1010

@@ -56,8 +56,8 @@ The validation on files are different to the others, but file input can still be
5656
All parameters can have default values, and automatic validation.
5757
`Route`, `Form`, `Json` and `Query` have the following options:
5858
* default: any, Specifies the default value for the field.
59-
* min_length: int, Specifies the minimum character length for a string input
60-
* max_length: int, Specifies the maximum character length for a string input
59+
* min_str_length: int, Specifies the minimum character length for a string input
60+
* max_str_length: int, Specifies the maximum character length for a string input
6161
* min_list_length: int, Specifies the minimum number of elements in a list
6262
* max_list_length: int, Specifies the maximum number of elements in a list
6363
* min_int: int, Specifies the minimum number for an int input
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from .exceptions import MissingInputError, InvalidParameterTypeError, ValidationError
2+
3+
__all__ = [
4+
"MissingInputError",
5+
"InvalidParameterTypeError",
6+
"ValidationError"
7+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class MissingInputError(Exception):
2+
"""Called if a user doesn't suppy a mandatory input"""
3+
def __init__(self, expected_name, expected_type):
4+
self.message = f"Missing required {expected_type.name} parameter '{expected_name}'."
5+
super().__init__(expected_type.name, expected_name)
6+
7+
def __str__(self):
8+
return self.message
9+
10+
class InvalidParameterTypeError(Exception):
11+
"""Called if the developer supplies a non-standard parameter type"""
12+
def __init__(self, invalid_type):
13+
self.message = (
14+
f"Invalid parameter type '{str(invalid_type)}' selected. "
15+
"Please refer to the flask-parameter-validation documentation."
16+
)
17+
super().__init__(self.message)
18+
19+
class ValidationError(Exception):
20+
"""Called if parameter validation fails"""
21+
def __init__(self, error_string, input_name, input_type):
22+
self.message = (
23+
f"Parameter '{input_name}' {error_string}"
24+
)
25+
super().__init__(error_string, input_name, input_type)
26+
27+
def __str__(self):
28+
return self.message

flask_parameter_validation/parameter_types/file.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
- Would originally be in Flask's request.file
44
- Value will be a FileStorage object
55
"""
6-
from .parameter import Parameter, ValidationError
6+
from .parameter import Parameter
77

88

99
class File(Parameter):
@@ -25,21 +25,19 @@ def validate(self, value):
2525
# We check mimetype, as it strips charset etc.
2626
if value.mimetype not in self.content_types:
2727
valid_types = "'" + "'/'".join(self.content_types) + "'"
28-
raise ValidationError(f"must have content-type {valid_types}.")
28+
raise ValueError(f"must have content-type {valid_types}.")
2929

3030
# Min content length validation
3131
if self.min_length is not None:
3232
if value.content_length < self.min_length:
33-
minlen = self.min_length
34-
raise ValidationError(
35-
f"must have a content-length larger than {minlen}."
33+
raise ValueError(
34+
f"must have a content-length larger than {self.min_length}."
3635
)
3736

3837
# Max content length validation
3938
if self.max_length is not None:
4039
if value.content_length > self.max_length:
41-
maxlen = self.max_length
42-
raise ValidationError(
43-
f"must have a content-length smaller than {maxlen}."
40+
raise ValueError(
41+
f"must have a content-length smaller than {self.max_length}."
4442
)
4543
return True

flask_parameter_validation/parameter_types/parameter.py

+55-58
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,14 @@
55
import re
66

77

8-
class ValidationError(Exception):
9-
pass
10-
11-
128
class Parameter:
139

1410
# Parameter initialisation
1511
def __init__(
1612
self,
1713
default=None, # any: default parameter value
18-
min_length=None, # int: min parameter length
19-
max_length=None, # int: max parameter length
14+
min_str_length=None, # int: min parameter length
15+
max_str_length=None, # int: max parameter length
2016
min_list_length=None, # int: min number of items in list
2117
max_list_length=None, # int: max number of items in list
2218
min_int=None, # int: min number (if val is int)
@@ -26,66 +22,67 @@ def __init__(
2622
pattern=None, # str: regexp pattern
2723
):
2824
self.default = default
29-
self.min_length = min_length
30-
self.max_length = max_length
25+
self.min_list_length = min_list_length
26+
self.max_list_length = max_list_length
27+
self.min_str_length = min_str_length
28+
self.max_str_length = max_str_length
3129
self.min_int = min_int
3230
self.max_int = max_int
3331
self.whitelist = whitelist
3432
self.blacklist = blacklist
3533
self.pattern = pattern
3634

3735
# Validator
38-
def validate(self, values):
39-
# Turn value into list if not already
40-
if type(values) is not list:
41-
values = [values]
42-
43-
# Check all values are valid
44-
for value in values:
45-
# Min length
46-
if self.min_length is not None:
47-
if len(value) < self.min_length:
48-
raise ValidationError(
49-
f"must be at least {self.min_length} characters."
50-
)
51-
# Max length
52-
if self.max_length is not None:
53-
if len(value) > self.max_length:
54-
raise ValidationError(
55-
f"must be a maximum of {self.max_length} characters."
36+
def validate(self, value):
37+
# Min length
38+
if self.min_str_length is not None:
39+
if len(value) < self.min_str_length:
40+
raise ValueError(
41+
f"must have at least {self.min_str_length} characters."
42+
)
43+
# Max length
44+
if self.max_str_length is not None:
45+
if len(value) > self.max_str_length:
46+
raise ValueError(
47+
f"must have a maximum of {self.max_str_length} characters."
48+
)
49+
# Whitelist
50+
if self.whitelist is not None:
51+
for char in str(value):
52+
if char not in self.whitelist:
53+
raise ValueError(
54+
f"must contain only characters: {self.whitelist}"
5655
)
57-
# Whitelist
58-
if self.whitelist is not None:
59-
for char in str(value):
60-
if char not in self.whitelist:
61-
raise ValidationError(
62-
f"must contain only characters: {self.whitelist}"
63-
)
64-
# Blacklist
65-
if self.blacklist is not None:
66-
for bad in self.blacklist:
67-
if bad in str(value):
68-
raise ValidationError(
69-
f"must not contain: {bad}"
70-
)
71-
# Min int
72-
if self.min_int is not None:
73-
if int(value) < self.min_int:
74-
raise ValidationError(
75-
f"must be larger than {self.min_int}."
76-
)
77-
# Max int
78-
if self.max_int is not None:
79-
if int(value) > self.max_int:
80-
raise ValidationError(
81-
f"must be smaller than {self.max_int}."
56+
# Blacklist
57+
if self.blacklist is not None:
58+
for bad in self.blacklist:
59+
if bad in str(value):
60+
raise ValueError(
61+
f"must not contain: {bad}"
8262
)
63+
# Min int
64+
if self.min_int is not None:
65+
if int(value) < self.min_int:
66+
raise ValueError(
67+
f"must be larger than {self.min_int}."
68+
)
69+
# Max int
70+
if self.max_int is not None:
71+
if int(value) > self.max_int:
72+
raise ValueError(
73+
f"must be smaller than {self.max_int}."
74+
)
8375

84-
# Regexp
85-
if self.pattern is not None:
86-
if not re.match(self.pattern, value):
87-
raise ValidationError(
88-
f"pattern does not match: {self.pattern}."
89-
)
76+
# Regexp
77+
if self.pattern is not None:
78+
if not re.match(self.pattern, value):
79+
raise ValueError(
80+
f"pattern does not match: {self.pattern}."
81+
)
82+
83+
return True
9084

91-
return True
85+
def convert(self, value, allowed_types):
86+
"""Some parameter types require manual type conversion (see Query)"""
87+
return value
88+

flask_parameter_validation/parameter_types/query.py

+24
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,27 @@ class Query(Parameter):
1010

1111
def __init__(self, default=None, **kwargs):
1212
super().__init__(default, **kwargs)
13+
14+
def convert(self, value, allowed_types):
15+
"""Convert query parameters to corresponding types."""
16+
if type(value) == str:
17+
# int conversion
18+
if int in allowed_types:
19+
try:
20+
value = int(value)
21+
except ValueError:
22+
pass
23+
# float conversion
24+
if float in allowed_types:
25+
try:
26+
value = float(value)
27+
except ValueError:
28+
pass
29+
# bool conversion
30+
if bool in allowed_types:
31+
if value.lower() == "true":
32+
value = True
33+
elif value.lower() == "false":
34+
value = False
35+
36+
return super().convert(value, allowed_types)

0 commit comments

Comments
 (0)