Skip to content
Snippets Groups Projects
Commit 587838b8 authored by Felix Blanke's avatar Felix Blanke
Browse files

Use schema to validate user JSON schedule

parent 3144bac3
No related branches found
No related tags found
1 merge request!268Merge fork for interoperability of KoMa solver
......@@ -10,9 +10,11 @@ from django import forms
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList
from django.utils.translation import gettext_lazy as _
from jsonschema.exceptions import best_match
from AKModel.availability.forms import AvailabilitiesFormMixin
from AKModel.models import Event, AKCategory, AKRequirement, Room, AKType
from AKModel.utils import construct_schema_validator
class DateTimeInput(forms.DateInput):
......@@ -300,19 +302,29 @@ class JSONScheduleImportForm(AdminIntermediateForm):
help_text=_("File with JSON data from the scheduling solver"),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.json_schema_validator = construct_schema_validator(
schema="solver-output.schema.json"
)
def _check_json_data(self, data: str):
try:
schedule = json.loads(data)
except json.JSONDecodeError as ex:
raise ValidationError(_("Cannot decode as JSON"), "invalid") from ex
for field in ["input", "scheduled_aks"]:
if not field in schedule:
error = best_match(self.json_schema_validator.iter_errors(schedule))
if error:
raise ValidationError(
_("Invalid JSON format: field '%(field)s' is missing"),
_("Invalid JSON format: %(msg)s at %(error_path)s"),
"invalid",
params={"field": field}
)
# TODO: Add further checks on json input
params={
"msg": error.message,
"error_path": error.json_path
}
) from error
return schedule
def clean(self):
......
......@@ -303,8 +303,8 @@ msgstr "Dekodierung als JSON fehlgeschlagen"
#: AKModel/forms.py:311
#, python-format
msgid "Invalid JSON format: field '%(field)s' is missing"
msgstr "Ungültige JSON-Eingabe: das Feld '%(field)s' fehlt"
msgid "Invalid JSON format: %(msg)s at %(error_path)s"
msgstr "Ungültige JSON-Eingabe: %(msg)s bei %(error_path)s"
#: AKModel/forms.py:321
msgid "Please enter data as a file OR via text, not both."
......@@ -1495,6 +1495,10 @@ msgstr "Zu Anforderungen gehörige AKs anzeigen"
msgid "Event Status"
msgstr "Eventstatus"
#, python-format
#~ msgid "Invalid JSON format: field '%(field)s' is missing"
#~ msgstr "Ungültige JSON-Eingabe: das Feld '%(field)s' fehlt"
#~ msgid "Opening time for expression of interest."
#~ msgstr "Öffnungszeitpunkt für die Angabe von Interesse an AKs."
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment