Skip to content

Commit 22aea4a

Browse files
committed
Refactor for tidyness and recognize contributors
1 parent 725e80b commit 22aea4a

File tree

3 files changed

+38
-23
lines changed

3 files changed

+38
-23
lines changed

Diff for: README.md

+8
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,11 @@ This method returns an object with the following structure:
216216
...
217217
]
218218
```
219+
220+
## Contributions
221+
Many thanks to all those who have made contributions to the project:
222+
* [d3-steichman](https://github.com/d3-steichman): API documentation, custom error handling, datetime validation and bug fixes
223+
* [Garcel](https://github.com/Garcel): Allow passing custom validator function
224+
* [iml1111](https://github.com/iml1111): Implement regex validation
225+
* [borisowww](https://github.com/borisowww): Fix file handling bugs
226+
* [Charlie-Mindified](https://github.com/Charlie-Mindified): Fix JSON handling bug

Diff for: flask_parameter_validation/parameter_validation.py

+24-23
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
import typing
2-
1+
import inspect
32
import re
4-
5-
from .parameter_types import Route, Json, Query, Form, File
6-
from .exceptions import MissingInputError, InvalidParameterTypeError, ValidationError
7-
from flask import request, current_app
83
from inspect import signature
4+
5+
from flask import request
96
from werkzeug.exceptions import BadRequest
10-
import inspect
7+
8+
from .exceptions import (InvalidParameterTypeError, MissingInputError,
9+
ValidationError)
10+
from .parameter_types import File, Form, Json, Query, Route
1111

1212
fn_list = dict()
13+
14+
1315
class ValidateParameters:
1416
@classmethod
1517
def get_fn_list(cls):
@@ -22,15 +24,19 @@ def __call__(self, f):
2224
"""
2325
Parent flow for validating each required parameter
2426
"""
25-
fsig = f.__module__+"."+f.__name__
27+
fsig = f.__module__ + "." + f.__name__
2628
argspec = inspect.getfullargspec(f)
2729
source = inspect.getsource(f)
2830
index = source.find("def ")
2931
decorators = []
3032
for line in source[:index].strip().splitlines():
3133
if line.strip()[0] == "@":
3234
decorators.append(line)
33-
fdocs = {"argspec": argspec, "docstring": f.__doc__.strip() if f.__doc__ else None, "decorators": decorators.copy()}
35+
fdocs = {
36+
"argspec": argspec,
37+
"docstring": f.__doc__.strip() if f.__doc__ else None,
38+
"decorators": decorators.copy(),
39+
}
3440
fn_list[fsig] = fdocs
3541

3642
def nested_func(**kwargs):
@@ -47,7 +53,7 @@ def nested_func(**kwargs):
4753
Json: json_input,
4854
Query: request.args.to_dict(),
4955
Form: request.form.to_dict(),
50-
File: request.files.to_dict()
56+
File: request.files.to_dict(),
5157
}
5258
# Step 2 - Get expected input details as dict
5359
expected_inputs = signature(f).parameters
@@ -97,8 +103,7 @@ def validate(self, expected_input, all_request_inputs):
97103
raise InvalidParameterTypeError(expected_delivery_type)
98104

99105
# Validate that user supplied input in expected delivery type (unless specified as Optional)
100-
user_input = all_request_inputs[expected_delivery_type.__class__].get(
101-
expected_name)
106+
user_input = all_request_inputs[expected_delivery_type.__class__].get(expected_name)
102107
if user_input is None:
103108
# If default is given, set and continue
104109
if expected_delivery_type.default is not None:
@@ -108,8 +113,7 @@ def validate(self, expected_input, all_request_inputs):
108113
if hasattr(expected_input_type, "__args__") and type(None) in expected_input_type.__args__:
109114
return user_input
110115
else:
111-
raise MissingInputError(
112-
expected_name, expected_delivery_type.__class__)
116+
raise MissingInputError(expected_name, expected_delivery_type.__class__)
113117

114118
# Skip validation if typing.Any is given
115119
if expected_input_type_str.startswith("typing.Any"):
@@ -119,7 +123,6 @@ def validate(self, expected_input, all_request_inputs):
119123
if expected_input_type_str.startswith("typing.Optional"):
120124
new_type = expected_input_type.__args__[0]
121125
expected_input_type = new_type
122-
expected_input_type_str_str = str(new_type)
123126

124127
# Prepare expected type checks for unions, lists and plain types
125128
if expected_input_type_str.startswith("typing.Union"):
@@ -149,14 +152,12 @@ def validate(self, expected_input, all_request_inputs):
149152
# Perform automatic type conversion for parameter types (i.e. "true" -> True)
150153
for count, value in enumerate(user_inputs):
151154
try:
152-
user_inputs[count] = expected_delivery_type.convert(
153-
value, expected_input_types)
155+
user_inputs[count] = expected_delivery_type.convert(value, expected_input_types)
154156
except ValueError as e:
155157
raise ValidationError(str(e), expected_name, expected_input_type)
156158

157159
# Validate that user type(s) match expected type(s)
158-
validation_success = all(
159-
type(inp) in expected_input_types for inp in user_inputs)
160+
validation_success = all(type(inp) in expected_input_types for inp in user_inputs)
160161

161162
# Validate that if lists are required, lists are given
162163
if expected_input_type_str.startswith("typing.List"):
@@ -165,12 +166,13 @@ def validate(self, expected_input, all_request_inputs):
165166

166167
# Error if types don't match
167168
if not validation_success:
168-
if hasattr(original_expected_input_type, "__name__") and not original_expected_input_type_str.startswith("typing."):
169+
if hasattr(original_expected_input_type, "__name__") and not original_expected_input_type_str.startswith(
170+
"typing."
171+
):
169172
type_name = original_expected_input_type.__name__
170173
else:
171174
type_name = original_expected_input_type_str
172-
raise ValidationError(
173-
f"must be type '{type_name}'", expected_name, original_expected_input_type)
175+
raise ValidationError(f"must be type '{type_name}'", expected_name, original_expected_input_type)
174176

175177
# Validate parameter-specific requirements are met
176178
try:
@@ -182,4 +184,3 @@ def validate(self, expected_input, all_request_inputs):
182184
if len(user_inputs) == 1:
183185
return user_inputs[0]
184186
return user_inputs
185-

Diff for: tox.ini

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[flake8]
2+
max-line-length = 120
3+
ignore = E501
4+
5+
[tool.black]
6+
line-length = 119

0 commit comments

Comments
 (0)