Skip to content
This repository has been archived by the owner on Mar 3, 2021. It is now read-only.

WIP: feat: parse answers instead of using flat fieldsets #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ verify_ssl = true
pytest = "*"
pytest-mock = "*"
pytest-cov = "*"
pdbpp = "*"

[packages]
requests = "*"
Expand Down
101 changes: 63 additions & 38 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 64 additions & 10 deletions caluma_client/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
from abc import ABC, abstractmethod

from .parser import parse_document

Expand Down Expand Up @@ -38,19 +39,28 @@ def getter(self):


class Form:
def __init__(self, raw):
def __init__(self, document, raw):
assert raw.get("__typename") == "Form", "raw must be a caluma `Form`"
self.root_document = document
self.raw = raw
self.fields = [Field(document, question) for question in self.raw["questions"]]

uuid = make_property(decode_id, "id")


class Question:
def __init__(self, raw):
def __init__(self, document, raw):
assert raw.get("__typename").endswith(
"Question"
), "raw must be a caluma `Question`"
self.question_type = raw["__typename"]
self.root_document = document
self.raw = raw
self.child_form = None
if self.question_type == "FormQuestion":
self.child_form = Form(document, self.raw["subForm"])
elif self.question_type == "TableQuestion":
self.child_form = Form(document, self.raw["rowForm"])


class Answer:
Expand All @@ -74,15 +84,27 @@ def value(self):


class Field:
def __init__(self, fieldset, raw):
assert "question" in raw, "Raw must contain Question"

self.fieldset = fieldset
def __init__(self, document, raw):
assert raw.get("__typename", "").endswith(
"Question"
), "Raw must contain Question"
# self.fieldset = fieldset
self.root_document = document
self.raw = raw

self.options = None # TODO?

question = make_property(Question, "question")
self.question = Question(document, self.raw)
# TODO answer

# question = make_property(Question, "question")
def _find_answer(self):
return next(
(
answer
for answer in self.root_document.raw["answers"]
if answer.get("question", {}).get("slug") == self.question.get("slug")
),
None,
)

@property
def answer(self):
Expand All @@ -108,9 +130,10 @@ class Document:
def __init__(self, raw):
assert raw.get("__typename") == "Document", "raw must be a caluma `Document`"
self.raw = raw
self.form = Form(self, raw.get("form"))

uuid = make_property(decode_id, "id")
root_form = make_property(Form, "rootForm")
# form = make_property(Form, "form")

@property
def pk(self):
Expand Down Expand Up @@ -169,3 +192,34 @@ def _find_answer(question):
@property
def field(self):
raise NotImplementedError


class Visitor(ABC):
def visit(self, node):
cls_name = type(node).__name__.lower()
method = getattr(self, "_visit_" + cls_name)
return method(node)

@abstractmethod
def _visit_document(self, node):
pass

@abstractmethod
def _visit_form(self, node):
pass

@abstractmethod
def _visit_field(self, node):
pass

@abstractmethod
def _visit_fieldset(self, node):
pass

@abstractmethod
def _visit_question(self, node):
pass

@abstractmethod
def _visit_answer(self, node):
pass
39 changes: 25 additions & 14 deletions caluma_client/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ def _unpack_dict(dictionary, levels):
return _unpack_dict(dictionary[current], levels[1:])


def _flatten(dictionary, key, func=lambda x: x):
return [func(edge["node"]) for edge in dictionary[key]["edges"]]


def parse_document(response, nesting=""):
if nesting:
levels = nesting.split(".")
Expand All @@ -19,26 +23,33 @@ def parse_document(response, nesting=""):

return {
**response,
"rootForm": parse_form(response["form"]),
"answers": [edge["node"] for edge in response["answers"]["edges"]],
"forms": parse_form_tree(response["form"]),
"form": parse_form(response["form"]),
"answers": _flatten(response, "answers", parse_answer),
}


def parse_form(response):
return {
**response,
"questions": [edge["node"] for edge in response["questions"]["edges"]],
}
return {**response, "questions": _flatten(response, "questions", parse_question)}


def parse_question(response):
ret = {**response}

def parse_form_tree(response):
form = parse_form(response)
ret = [form]
if "subForm" in response:
ret["subForm"] = parse_form(response["subForm"])
elif "rowForm" in response:
ret["rowForm"] = parse_form(response["rowForm"])
elif "choiceOptions" in response:
ret["choiceOptions"] = _flatten(response, "choiceOptions")
elif "multipleChoiceQuestion" in response:
ret["multipleChoiceQuestion"] = _flatten(response, "multipleChoiceQuestion")

return ret

for question in form["questions"]:
subform = question.get("subForm")
if subform:
ret.extend(parse_form_tree(subform))

def parse_answer(response):
ret = {**response}
ret["question"] = parse_question(response["question"])
if "tableValue" in response:
ret["tableValue"] = [parse_document(doc) for doc in response["tableValue"]]
return ret