forked from dapper91/pydantic-xml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunion_models.py
72 lines (59 loc) · 1.49 KB
/
union_models.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from typing import Dict, List, Union
from pydantic_xml import BaseXmlModel, attr, element
# [model-start]
class Event(BaseXmlModel):
timestamp: float = attr()
class KeyboardEvent(Event, tag='keyboard'):
type: str = attr()
key: str = element()
class MouseEvent(Event, tag='mouse'):
position: Dict[str, int] = element()
class Log(BaseXmlModel, tag='log'):
events: List[Union[KeyboardEvent, MouseEvent]] = element()
# [model-end]
# [xml-start]
xml_doc = '''
<log>
<mouse timestamp="1674999183.5486422">
<position x="234" y="345"/>
</mouse>
<keyboard timestamp="1674999184.227246"
type="KEYDOWN">
<key>CTRL</key>
</keyboard>
<keyboard timestamp="1674999185.6342669"
type="KEYDOWN">
<key>C</key>
</keyboard>
<mouse timestamp="1674999186.270716">
<position x="236" y="211"/>
</mouse>
</log>
''' # [xml-end]
# [json-start]
json_doc = '''
{
"events": [
{
"timestamp": 1674999183.5486422,
"position": {"x": 234, "y": 345}
},
{
"timestamp": 1674999184.227246,
"type": "KEYDOWN",
"key": "CTRL"
},
{
"timestamp": 1674999185.6342669,
"type": "KEYDOWN",
"key": "C"
},
{
"timestamp": 1674999186.270716,
"position": {"x": 236, "y": 211}
}
]
}
''' # [json-end]
log = Log.from_xml(xml_doc)
assert log == Log.parse_raw(json_doc)