icp/oer/exercise-formats/choice/multiple/ExerciseHandler.py

67 lines
1.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import json
import re
import crypt
print("Handler choice/multiple loaded!")
# helper
# analog to value of html input field (checkbox/radio) it feels kinda odd to
# use this, maybe settle with another hash function than the default this only
# requires performance not cryptographic security
def hash(arg):
return crypt.crypt(str(arg))
def parse_choice(raw_choice):
choice = {"text": "", "is": "incorrect", "value": ""}
result = re.findall(r"^([*!]?)(.*)$", raw_choice, re.DOTALL)
value = hash(result[0][1])
if result[0][0] == '*':
choice = {"text": result[0][1], "is": "correct", "value": value}
elif result[0][0] == '!':
choice = {"text": result[0][1], "is": "required", "value": value}
else:
choice = {"text": result[0][1], "is": "incorrect", "value": value}
return choice
class ExerciseHandler(object):
def __init__(self, parser=None):
self.parser = parser
self.data = {'choices': [''], 'question': ''}
print("ExerciseHandler choice/multiple")
print("parser.path", parser.path)
item = self.parser.item
data = self.data
# enable grading for this exercise type
item.grading = True
item.content = self.parser.get_exercise_content()
data['question'] = self.parser.get_file_content('question')
# import and sanitize choices
data['choices'] = self.parser.get_file_content('choices').split('\n')
for i,choice in enumerate(data['choices']):
data['choices'][i] = parse_choice(choice)
# determine how to render choices
data['input_type'] = "checkbox"
if 'choose' in parser.meta:
if parser.meta['choose'] == "one":
data['input_type'] = "radio"
item.data = json.dumps(self.data)
item.save()