Created
May 17, 2021 10:47
-
-
Save M0r13n/2ca342eeb178b3f95f8fe62f4d70eb3a to your computer and use it in GitHub Desktop.
Related mapping examle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import json | |
from enum import Enum | |
import related | |
from attr import attrib | |
from related import to_model, TypedSequence | |
class Files(Enum): | |
DOC = "responses/document.json" | |
FIELD_DOCUMENT = "responses/field_document.json" | |
FIELD_ROOT = "responses/field_root.json" | |
FIELD_CAD = "responses/field_cad_document.json" | |
CLASSIFIERS = { | |
"/": Files.FIELD_DOCUMENT, | |
"/Document/": Files.FIELD_ROOT, | |
"/Document/CAD-Dokument/": Files.FIELD_CAD, | |
} | |
def load_json(file_name: str): | |
with open(file_name) as fd: | |
return json.loads(fd.read()) | |
def http_get(typ: Files): | |
return load_json(typ.value) | |
def HTTPResolvableField(cls, repr=True, cmp=True, key=None): | |
def convert(values): | |
values = values or [] | |
values = [cls.http_fetch(value) for value in values] | |
args = [to_model(cls, value) for value in values] | |
return TypedSequence(cls=cls, args=args) | |
return attrib(converter=convert, | |
validator=None, repr=repr, cmp=cmp, | |
metadata=dict(key=key)) | |
############ Actual Classes ################ | |
@related.immutable() | |
class FieldSchema(object): | |
id = related.IntegerField(key="Id") | |
options = related.IntegerField(key="Options") | |
path = related.StringField(key="FieldPath") | |
type = related.StringField(key="FieldType") | |
name = related.StringField(key="Title01") | |
name_eng = related.StringField(key="Title02") | |
var_name = related.StringField(key="Title99") | |
default_value = related.StringField(key="DefaultValue", required=False) | |
documentation = related.StringField(key="Documentation", required=False) | |
@related.immutable() | |
class Classifier(object): | |
field_schemata = related.SequenceField(FieldSchema) | |
@classmethod | |
def http_fetch(cls, value: str): | |
return http_get(Files(CLASSIFIERS[value]))[1] | |
@related.immutable() | |
class Document(object): | |
classification = HTTPResolvableField(Classifier, key="Classification") | |
fields = related.ChildField(dict, key="FieldValues") | |
if __name__ == "__main__": | |
doc = related.to_model(Document, http_get(Files.DOC)[0]) | |
for classifier in doc.classification: | |
print(classifier.field_schemata) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment