| Total Complexity | 2 |
| Total Lines | 30 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | from enum import Enum |
||
| 2 | from functools import wraps |
||
| 3 | from typing import Type |
||
| 4 | |||
| 5 | from flask import abort, request |
||
| 6 | from pydantic import BaseModel |
||
| 7 | from pydantic.error_wrappers import ValidationError |
||
| 8 | |||
| 9 | from app.context import context_property |
||
| 10 | |||
| 11 | |||
| 12 | class PayloadLocation(Enum): |
||
| 13 | ARGS = 'args' |
||
| 14 | JSON = 'json' |
||
| 15 | |||
| 16 | |||
| 17 | def validate_with_pydantic(payload_location: PayloadLocation, model: Type[BaseModel]): |
||
| 18 | def decorator(fn): |
||
| 19 | @wraps(fn) |
||
| 20 | def wrapper(*args, **kwargs): |
||
| 21 | try: |
||
| 22 | instance = model(**getattr(request, payload_location.value)) |
||
| 23 | |||
| 24 | context_property.request_payload = instance |
||
| 25 | return fn(*args, **kwargs) |
||
| 26 | except ValidationError as e: |
||
| 27 | abort(400, e.json()) |
||
| 28 | return wrapper |
||
| 29 | return decorator |
||
| 30 |