-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.py
More file actions
33 lines (28 loc) · 1.24 KB
/
Copy pathhandler.py
File metadata and controls
33 lines (28 loc) · 1.24 KB
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
import sys
from typing import Any, Callable, Generator, Iterable, Dict
class ValidationError(ValueError):
pass
class LoopHandler:
def __init__(self, schemas: Dict[str, Callable[[Any], bool]]):
self.schemas = schemas
def process(self, items: Iterable[Dict[str, Any]]) -> Generator[Dict[str, Any], None, None]:
for index, item in enumerate(items):
try:
if not isinstance(item, dict):
raise ValidationError('Item is not a dictionary structure')
for key, validator in self.schemas.items():
if key not in item:
raise ValidationError(f'Missing required field: {key}')
if not validator(item[key]):
raise ValidationError(f'Validation failed for \'{key}\': {item[key]}')
yield {
'id': index,
'payload': {k: v for k, v in item.items() if not k.startswith('_')},
'valid': True
}
except ValidationError as exc:
yield {
'id': index,
'error': str(exc),
'valid': False
}