Skip to content

feat(webserver): introduce Attempt.data to store dynamic data #207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 22, 2025
Merged
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
14 changes: 14 additions & 0 deletions frontend/src/types/AttemptRenderData.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type RenderError =
| UnknownElementError
| UnknownAttributeError
| DuplicateNameError
| ReservedNameError
| XMLSyntaxError
/**
* Collects render errors and provides a sorted iterator.
Expand Down Expand Up @@ -167,6 +168,19 @@ export interface DuplicateNameError {
*/
line: number | null
}
/**
* Reserved input name.
*/
export interface ReservedNameError {
template: string
template_kwargs: TemplateKwargs
kind: 'reserved_name'
type: string
/**
* Original line number where the error occurred or None if unknown.
*/
line: number | null
}
/**
* Syntax error while parsing the XML.
*/
Expand Down
12 changes: 12 additions & 0 deletions questionpy_sdk/webserver/controllers/attempt/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class AttemptTemplateContext(TypedDict):
import_map: dict[str, str]
javascript_calls: list[JsModuleCall]
stylesheet_urls: list[str]
data: dict[str, JsonValue]


@dataclass
Expand Down Expand Up @@ -160,6 +161,7 @@ async def _render_ui(
"import_map": await self._get_import_map(),
"javascript_calls": self._get_js_calls(attempt, display_options),
"stylesheet_urls": self._get_stylesheet_urls(attempt),
"data": self._get_dynamic_data(last_attempt_data),
}

render_errors: SectionErrorMap = {}
Expand All @@ -175,6 +177,16 @@ async def _render_ui(

return template_context, render_errors

def _get_dynamic_data(self, last_attempt_data: dict[str, JsonValue] | None) -> dict[str, JsonValue]:
if not last_attempt_data:
return {}

data = last_attempt_data.get("data", {})
if not isinstance(data, dict):
return {}

return data

async def _get_import_map(self) -> dict[str, str]:
worker: Worker
async with self._worker_pool.get_worker(self._package_location, 0, None) as worker:
Expand Down
14 changes: 14 additions & 0 deletions questionpy_sdk/webserver/controllers/attempt/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
| UnknownElementError
| UnknownAttributeError
| DuplicateNameError
| ReservedNameError
| XMLSyntaxError,
Field(discriminator="kind"),
]
Expand Down Expand Up @@ -284,6 +285,19 @@ def __init__(self, element: etree._Element, name: str, other_element: etree._Ele
)


class ReservedNameError(RenderElementError):
"""Reserved input name."""

kind: Literal["reserved_name"] = "reserved_name"

def __init__(self, element: etree._Element, name: str):
super().__init__(
element,
"{element} cannot use the reserved name {name}.",
{"name": name},
)


class XMLSyntaxError(BaseRenderError):
"""Syntax error while parsing the XML."""

Expand Down
20 changes: 15 additions & 5 deletions questionpy_sdk/webserver/controllers/attempt/question_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
InvalidContentError,
PlaceholderReferenceError,
RenderErrorCollection,
ReservedNameError,
UnknownAttributeError,
UnknownElementError,
XMLSyntaxError,
Expand Down Expand Up @@ -732,8 +733,13 @@ def _check_input_names(self) -> None:
for current_element in _assert_element_list(
self._xpath("(//xhtml:button | //xhtml:input | //xhtml:select | //xhtml:textarea)[@name]")
):
# Get name, type, and value of the current element.
name = str(current_element.attrib["name"])

if name == "data":
reserved_name_error = ReservedNameError(element=current_element, name=name)
self.errors.insert(reserved_name_error)
continue

current_type = current_element.get("type", "text")
current_value = current_element.get("value", "on")

Expand All @@ -748,13 +754,17 @@ def _check_input_names(self) -> None:

if current_type not in {"checkbox", "radio"}:
# Duplicate names are not allowed for other elements.
error = DuplicateNameError(element=current_element, name=name, other_element=other_element)
self.errors.insert(error)
duplicate_name_error = DuplicateNameError(
element=current_element, name=name, other_element=other_element
)
self.errors.insert(duplicate_name_error)
continue

# Check that the types match and the value is unique.
if other_type != current_type or current_value in values:
error = DuplicateNameError(element=current_element, name=name, other_element=other_element)
self.errors.insert(error)
duplicate_name_error = DuplicateNameError(
element=current_element, name=name, other_element=other_element
)
self.errors.insert(duplicate_name_error)
else:
values.add(current_value)
24 changes: 24 additions & 0 deletions questionpy_sdk/webserver/templates/attempt.html.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@
}
}

// Add dynamic data.
formData['data'] = attempt.data

return formData
}

Expand Down Expand Up @@ -175,6 +178,7 @@
#specificFeedback;
#rightAnswer;
#roles;
#data;
#environment;

/**
Expand All @@ -188,6 +192,7 @@
* @param {?Element} specificFeedbackElement
* @param {?Element} rightAnswer
* @param {string[]} roles
* @param {Object.<string, any>} data
*/
constructor(
readOnly,
Expand All @@ -200,6 +205,7 @@
specificFeedbackElement,
rightAnswer,
roles,
data,
) {
this.#readOnly = readOnly;
this.#showGeneralFeedback = showGeneralFeedback;
Expand All @@ -211,6 +217,7 @@
this.#specificFeedback = specificFeedbackElement;
this.#rightAnswer = rightAnswer;
this.#roles = roles;
this.#data = data;
this.#environment = new AttemptEnvironment("SDK", 0);
}

Expand Down Expand Up @@ -311,6 +318,22 @@
return this.#roles;
}

/**
* Get the object used to store dynamic data.
*
* @note
* This object will be serialized to JSON by using `JSON.stringify` and therefore follows the conversion
* rules of this function. This also means that the keys of (nested) objects will be converted to
* strings.
*
* The depth of the object should not exceed 16.
*
* @returns {Object.<string, any>}
*/
get data() {
return this.#data;
}

/**
* Get information about the current environment.
*
Expand All @@ -332,6 +355,7 @@
document.getElementById("container-specific-feedback"),
document.getElementById("container-right-answer"),
[{{ display_options.roles|map('lower')|map('tojson')|join(',') }}],
{{ data|tojson }},
);

{% for javascript_call in javascript_calls %}
Expand Down