|
1 | 1 | from functools import wraps |
2 | 2 | from typing import Any |
3 | | -from typing import Dict |
4 | 3 | from typing import get_args |
5 | 4 | from typing import get_origin |
| 5 | +from typing import get_type_hints |
6 | 6 | from typing import Optional |
7 | 7 | from typing import Type |
8 | 8 | from typing import Union |
@@ -173,7 +173,6 @@ def _check_type(value: Any, expected_type: Type, allow_empty: bool = False, curr |
173 | 173 |
|
174 | 174 |
|
175 | 175 | def validate_params( |
176 | | - parameters: Dict[Any, Any], |
177 | 176 | allow_empty: bool = False, |
178 | 177 | ): |
179 | 178 | """ |
@@ -241,6 +240,14 @@ def example(): |
241 | 240 | def decorator(fn): |
242 | 241 | @wraps(fn) |
243 | 242 | def wrapper(*args, **kwargs): |
| 243 | + |
| 244 | + # Load expected parameter types from function type hints |
| 245 | + parameters = get_type_hints(fn) |
| 246 | + |
| 247 | + # Remove return value type hints |
| 248 | + if "return" in parameters.keys(): |
| 249 | + del parameters["return"] |
| 250 | + |
244 | 251 | try: |
245 | 252 | data = request.get_json() |
246 | 253 | except BadRequest: |
@@ -271,6 +278,13 @@ def wrapper(*args, **kwargs): |
271 | 278 | if key in parameters and not _check_type(data[key], parameters[key], allow_empty): |
272 | 279 | raise BadRequestError(f"Wrong type for key {key}.", f"It should be {parameters[key]}") |
273 | 280 |
|
| 281 | + for key in parameters: |
| 282 | + if _is_optional(parameters[key]) and key not in data: |
| 283 | + kwargs[key] = None |
| 284 | + |
| 285 | + else: |
| 286 | + kwargs[key] = data[key] |
| 287 | + |
274 | 288 | return fn(*args, **kwargs) |
275 | 289 |
|
276 | 290 | return wrapper |
|
0 commit comments