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

Use schema to validate user JSON schedule

parent 7065bc09
No related branches found
No related tags found
1 merge request!24Feature: JSON import file upload button and schema input validation
...@@ -10,9 +10,11 @@ from django import forms ...@@ -10,9 +10,11 @@ from django import forms
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList from django.forms.utils import ErrorList
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from jsonschema.exceptions import best_match
from AKModel.availability.forms import AvailabilitiesFormMixin from AKModel.availability.forms import AvailabilitiesFormMixin
from AKModel.models import Event, AKCategory, AKRequirement, Room, AKType from AKModel.models import Event, AKCategory, AKRequirement, Room, AKType
from AKModel.utils import construct_schema_validator
class DateTimeInput(forms.DateInput): class DateTimeInput(forms.DateInput):
...@@ -300,19 +302,29 @@ class JSONScheduleImportForm(AdminIntermediateForm): ...@@ -300,19 +302,29 @@ class JSONScheduleImportForm(AdminIntermediateForm):
help_text=_("File with JSON data from the scheduling solver"), 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): def _check_json_data(self, data: str):
try: try:
schedule = json.loads(data) schedule = json.loads(data)
except json.JSONDecodeError as ex: except json.JSONDecodeError as ex:
raise ValidationError(_("Cannot decode as JSON"), "invalid") from 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))
raise ValidationError( if error:
_("Invalid JSON format: field '%(field)s' is missing"), raise ValidationError(
"invalid", _("Invalid JSON format: %(msg)s at %(error_path)s"),
params={"field": field} "invalid",
) params={
# TODO: Add further checks on json input "msg": error.message,
"error_path": error.json_path
}
) from error
return schedule return schedule
def clean(self): def clean(self):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment