Skip to content
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

#140: generated_id #144

Open
wants to merge 4 commits into
base: dev
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
2 changes: 2 additions & 0 deletions examples/multichoice/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
__pycache__
/dist
8 changes: 8 additions & 0 deletions examples/multichoice/python/local/multichoice/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# This file is part of the QuestionPy SDK. (https://questionpy.org)
# The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md.
# (c) Technische Universität Berlin, innoCampus <[email protected]>
from questionpy import make_question_type_init

from .question_type import MultichoiceQuestion

init = make_question_type_init(MultichoiceQuestion)
18 changes: 18 additions & 0 deletions examples/multichoice/python/local/multichoice/form.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from questionpy.form import FormModel, OptionEnum, checkbox, generated_id, option, repeat, select, text_input


class ChoiceMode(OptionEnum):
SELECT = option("<select> element")
RADIO = option('<input type="radio"> element')


class Choice(FormModel):
id: str = generated_id()
text: str = text_input("Text", required=True)
correct: bool = checkbox("Korrekt")


class MultichoiceFormModel(FormModel):
description: str = text_input("Beschreibung", required=True)
mode: ChoiceMode = select("Auswahlelement", ChoiceMode, required=True)
choices: list[Choice] = repeat(Choice, initial=3, minimum=2)
35 changes: 35 additions & 0 deletions examples/multichoice/python/local/multichoice/question_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import Any

from questionpy import Attempt, Question, ResponseNotScorableError

from .form import ChoiceMode, MultichoiceFormModel


class MultichoiceAttempt(Attempt):
def _compute_score(self) -> float:
if not self.response or "choice" not in self.response:
msg = "'choice' is missing"
raise ResponseNotScorableError(msg)

chosen_id = self.response["choice"]
correct_choice_ids = [choice.id for choice in self.question.options.choices if choice.correct]

if chosen_id in correct_choice_ids:
return 1

return 0

def __init__(self, *args: Any):
super().__init__(*args)

self.placeholders["description"] = self.question.options.description

@property
def formulation(self) -> str:
return self.jinja2.get_template("local.multichoice/formulation.xhtml.j2").render(ChoiceMode=ChoiceMode)


class MultichoiceQuestion(Question):
attempt_class = MultichoiceAttempt

options: MultichoiceFormModel
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<div xmlns="http://www.w3.org/1999/xhtml"
xmlns:qpy="http://questionpy.org/ns/question">
<p><?p description?></p>
<p>
{% if question.options.mode == ChoiceMode.SELECT %}
<label>
Auswahl:

<select name="choice" qpy:shuffle-contents="">
{% for choice in question.options.choices %}
<option value="{{ choice.id }}">{{ choice.text }}</option>
{% endfor %}
</select>
</label>
{% else %}
<fieldset style="display: flex; flex-direction: column" qpy:shuffle-contents="">
{% for choice in question.options.choices %}
<label><input type="radio" name="choice" value="{{ choice.id }}"/> {{ choice.text }}</label>
{% endfor %}
</fieldset>
{% endif %}
</p>
</div>
9 changes: 9 additions & 0 deletions examples/multichoice/qpy_config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
short_name: multichoice
namespace: local
version: 0.1.0
api_version: "0.1"
author: Jane Doe <[email protected]>
name:
de: Multiple-Choice
en: Multiple-Choice
languages: [de, en]
10 changes: 5 additions & 5 deletions poetry.lock

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

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ python = "^3.11"
aiohttp = "^3.9.3"
pydantic = "^2.6.4"
PyYAML = "^6.0.1"
questionpy-server = { git = "https://github.com/questionpy-org/questionpy-server.git", rev = "3ae1fcc79b1c9440d40cbe5b48d16ac4c68061b9" }
questionpy-server = {git = "https://github.com/questionpy-org/questionpy-server.git", rev = "15db8d8cf59d364e21a226fdf477869c9894bdf9"}
jinja2 = "^3.1.3"
aiohttp-jinja2 = "^1.6"
lxml = "~5.1.0"
Expand Down
1 change: 1 addition & 0 deletions questionpy/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@


def get_mro_type_hint(klass: type, attr_name: str, bound: _T) -> _T:
# FIXME: This function is called too early, when the classes referenced in forward refs may not be defined yet.
for superclass in klass.mro():
hints = get_type_hints(superclass)
if attr_name in hints:
Expand Down
4 changes: 4 additions & 0 deletions questionpy/form/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
CheckboxGroupElement,
FormElement,
FormSection,
GeneratedIdElement,
GroupElement,
HiddenElement,
Option,
Expand All @@ -63,6 +64,7 @@
checkbox,
does_not_equal,
equals,
generated_id,
group,
hidden,
is_checked,
Expand All @@ -86,6 +88,7 @@
"FormElement",
"FormModel",
"FormSection",
"GeneratedIdElement",
"GroupElement",
"HiddenElement",
"Option",
Expand All @@ -100,6 +103,7 @@
"checkbox",
"does_not_equal",
"equals",
"generated_id",
"group",
"hidden",
"is_checked",
Expand Down
18 changes: 18 additions & 0 deletions questionpy/form/_dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from questionpy_common.conditions import Condition, DoesNotEqual, Equals, In, IsChecked, IsNotChecked
from questionpy_common.elements import (
CheckboxElement,
GeneratedIdElement,
GroupElement,
HiddenElement,
Option,
Expand Down Expand Up @@ -732,6 +733,9 @@ def repeat(
) -> list[_F]:
"""Repeats a sub-model, allowing the user to add new repetitions with the click of a button.

Be aware that the index of repetitions may change when earlier ones are removed. In order to distinguish
repetitions, look into adding a [generated_id][] field to the repeated model.

Args:
model (type[FormModel]): A `FormModel` subclass containing the fields to repeat.
initial: Number of repetitions to show when the form is first loaded.
Expand Down Expand Up @@ -772,6 +776,20 @@ def repeat(
)


def generated_id() -> str:
"""Generates a unique ID which won't change across form saves.

This is especially useful to distinguish repetitions without relying on their index, which may change when
repetitions are removed.
"""
return cast(
str,
_FieldInfo(
type=str, build=lambda name: GeneratedIdElement(name=name), pydantic_field_info=FieldInfo(frozen=True)
),
)


def is_checked(name: str) -> IsChecked:
"""Condition on a checkbox being checked.

Expand Down
3 changes: 3 additions & 0 deletions questionpy_sdk/webserver/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
CheckboxElement,
CheckboxGroupElement,
FormElement,
GeneratedIdElement,
GroupElement,
HiddenElement,
OptionsFormDefinition,
Expand All @@ -23,6 +24,7 @@
CxdCheckboxGroupElement,
CxdFormElement,
CxdFormSection,
CxdGeneratedIdElement,
CxdGroupElement,
CxdHiddenElement,
CxdOptionsFormDefinition,
Expand All @@ -43,6 +45,7 @@
RadioGroupElement: CxdRadioGroupElement,
SelectElement: CxdSelectElement,
HiddenElement: CxdHiddenElement,
GeneratedIdElement: CxdGeneratedIdElement,
}


Expand Down
15 changes: 14 additions & 1 deletion questionpy_sdk/webserver/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from re import Pattern, sub
from typing import Annotated, Any, TypeAlias
from uuid import uuid4

from pydantic import BaseModel, Field, computed_field

Expand All @@ -12,6 +13,7 @@
CheckboxGroupElement,
FormElement, # noqa: F401
FormSection,
GeneratedIdElement,
GroupElement,
HiddenElement,
Option,
Expand Down Expand Up @@ -212,6 +214,16 @@ def __init__(self, **data: Any):
super().__init__(**data, elements=[])


class CxdGeneratedIdElement(GeneratedIdElement, _CxdFormElement):
cxd_value: str | None = None

def add_form_data_value(self, element_form_data: Any) -> None:
if element_form_data:
self.cxd_value = element_form_data
else:
self.cxd_value = str(uuid4())


CxdFormElement: TypeAlias = Annotated[
CxdStaticTextElement
| CxdTextInputElement
Expand All @@ -222,7 +234,8 @@ def __init__(self, **data: Any):
| CxdSelectElement
| CxdHiddenElement
| CxdGroupElement
| CxdRepetitionElement,
| CxdRepetitionElement
| CxdGeneratedIdElement,
Field(discriminator="kind"),
]

Expand Down
15 changes: 10 additions & 5 deletions questionpy_sdk/webserver/question_ui/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@


def _format_human_readable_list(values: Collection[str], opening: str, closing: str) -> str:
if not values:
return ""

*values, last_value = values
last_value = f"{opening}{last_value}{closing}"
if not values:
Expand Down Expand Up @@ -150,16 +153,18 @@ class PlaceholderReferenceError(RenderElementError):
"""An unknown or no placeholder was referenced."""

def __init__(self, element: etree._Element, placeholder: str | None, available: Collection[str]):
template_kwargs: dict[str, str | Collection[str]] = {}
if placeholder is None:
template = "No placeholder was referenced."
template_kwargs = {}
else:
template = "Referenced placeholder {placeholder} was not found."
template_kwargs["placeholder"] = placeholder

if len(available) == 0:
provided = "No placeholders were provided."
template += " No placeholders were provided."
else:
provided = "These are the provided placeholders: {available}."
template = f"Referenced placeholder {{placeholder}} was not found. {provided}"
template_kwargs = {"placeholder": placeholder, "available": available}
template += " These are the provided placeholders: {available}."
template_kwargs["available"] = available

super().__init__(
element=element,
Expand Down
20 changes: 17 additions & 3 deletions questionpy_sdk/webserver/routes/options.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# This file is part of the QuestionPy SDK. (https://questionpy.org)
# The QuestionPy SDK is free software released under terms of the MIT license. See LICENSE.md.
# (c) Technische Universität Berlin, innoCampus <[email protected]>

from http.client import UNPROCESSABLE_ENTITY
from typing import TYPE_CHECKING, Never
from uuid import uuid4

import aiohttp_jinja2
from aiohttp import web
Expand Down Expand Up @@ -69,8 +69,22 @@ async def repeat_element(request: web.Request) -> web.Response:
data = await request.json()
question_form_data = parse_form_data(data["form_data"])
repetition_list = get_nested_form_data(question_form_data, data["repetition_name"])
if isinstance(repetition_list, list) and "increment" in data:
repetition_list.extend([repetition_list[-1]] * int(data["increment"]))

if not isinstance(repetition_list, list) or "increment" not in data:
raise web.HTTPUnprocessableEntity

new_repetition_items: list[dict] = [repetition_list[-1].copy() for _ in range(int(data["increment"]))]
# ID elements must be unique, so new items need a new value.
for new_repetition_item in new_repetition_items:
id_element_names = new_repetition_item.get("qpy_id_elements")
if not isinstance(id_element_names, list):
continue

for id_element_name in id_element_names:
if id_element_name in new_repetition_item:
new_repetition_item[id_element_name] = str(uuid4())

repetition_list.extend(new_repetition_items)

try:
await _save_updated_form_data(question_form_data, webserver)
Expand Down
4 changes: 4 additions & 0 deletions questionpy_sdk/webserver/templates/elements/id.html.jinja2
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<input type="hidden" name="{{ element_reference }}"
value="{{ element.cxd_value }}" id="{{ element.id }}">
<input type="hidden" name="{{ path_list_to_string(element.path[:-1] + ['qpy_id_elements']) + "_[]" }}"
value="{{ element.name }}">
Loading
Loading