~kf5jwc/sms-printer

ref: 83f141d0bd34662859108a44509a56292fe3bc1d sms-printer/sms_broker_parsers/parsers/json/__init__.py -rw-r--r-- 1.3 KiB View raw
83f141d0 — Kyle Jones Break out the library. 2 years ago
                                                                                
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
This module provides the filtering and parsing. They currently only
provide a list of messages with the sender number and message text.

Each module has a `SCHEMA` and a `Parser(Parser_Base)`

The `SCHEMA` is matched against incoming messages to determine the
correct parser to use for a message.

Adding more is simple enough. Define a new parser and its schema in
its own module next to the others, and add it to `SCHEMAS` here.

I use `genson` to generate schemas based on an example message.
"""


import automodinit
from typing import Dict, Type
from jsonschema import validate
from jsonschema.exceptions import ValidationError
import json
from ...errors import NoMatchingSchema
from ...types import Parser_Base

MIMETYPES = ["application/json", "application/json+xml"]
SCHEMAS: Dict[str, Type[Parser_Base]] = {}
__all__ = []

automodinit.automodinit(__name__, __file__, globals())
del automodinit
for module_name in __all__:
    mod = globals()[module_name]
    SCHEMAS[getattr(mod, "SCHEMA")] = getattr(mod, "Parser")


def parse_sms(sms_input: str) -> Type[Parser_Base]:
    for schema, sms_parser in SCHEMAS.items():
        try:
            validate(sms_input, json.loads(schema))
            return sms_parser(sms_input)
        except ValidationError:
            continue

    raise NoMatchingSchema


__all__ = ["MIMETYPES", "parse_sms"]