diff options
-rw-r--r-- | requirements/requirements-common.txt | 1 | ||||
-rw-r--r-- | yaksh/demo_templates/yaml_question_template | 90 | ||||
-rw-r--r-- | yaksh/fixtures/demo_questions.zip | bin | 4430 -> 1712 bytes | |||
-rw-r--r-- | yaksh/models.py | 78 | ||||
-rw-r--r-- | yaksh/static/yaksh/js/show_question.js | 4 | ||||
-rw-r--r-- | yaksh/templates/yaksh/showquestions.html | 86 | ||||
-rw-r--r-- | yaksh/test_models.py | 21 | ||||
-rw-r--r-- | yaksh/test_views.py | 2 | ||||
-rw-r--r-- | yaksh/urls.py | 4 | ||||
-rw-r--r-- | yaksh/views.py | 19 |
10 files changed, 238 insertions, 67 deletions
diff --git a/requirements/requirements-common.txt b/requirements/requirements-common.txt index 53a44a4..6169c9b 100644 --- a/requirements/requirements-common.txt +++ b/requirements/requirements-common.txt @@ -6,3 +6,4 @@ tornado selenium==2.53.6 coverage psutil +pyyaml
\ No newline at end of file diff --git a/yaksh/demo_templates/yaml_question_template b/yaksh/demo_templates/yaml_question_template new file mode 100644 index 0000000..4de9274 --- /dev/null +++ b/yaksh/demo_templates/yaml_question_template @@ -0,0 +1,90 @@ +--- +# Yaml Template for writing questions +# Always keep the name of this file as questions_dump.yaml +# Zip this file with necessary dependent files. + +active: true +# question status = true or false + +description: "Write a function <code>product(a,b)</code> which will take + two integers and return the product of it.<br> + " +# Entire question description. + +files: [] +# [[file name, zip_extract_status=true or false]] + +language: python +# bash, scilab, python, c/c++, java + +points: 1.0 +# marks in float + +snippet: "def sum(a,b):" +# adds in the student's code area + +summary: Product of two numbers +# one line short Summary +testcase: +- test_case_type: standardtestcase + test_case: assert sum(3,5) == 15 + test_case_args: "" + weight: 1.0 +#testcase 1 + +- test_case_type: standardtestcase + test_case: assert sum(10,10) == 100 + test_case_args: "" + weight: 1.0 +#testcase 2 + +# for standard testcase: + # - test_case_type: standardtestcase + # test_case: test case in the selected language + # test_case_args: command line args (only for bash) + # weight: weightage for each course + +# for stdIO testcase: + # - test_case_type: stdiobasedtestcase + # expected_input: Standard input given to the students' code. (Optional) + # expected_input: Standard output expected from the students' code. + # weight: weightage for each course + +# for MCQ/MCC testcase: + # - test_case_type: mcqtestcase + # options: MCQ/MCC option. + # correct: true or false. + +# for Hook testcase: + # - test_case_type: hooktestcase + # hook_code: Selected language code written by moderator (Optional) + # weight: weightage for each course + +# for Integer testcase: + # - test_case_type: integertestcase + # correct: Correct integer value + +# for Float testcase: + # - test_case_type: floattestcase + # correct: Correct float value + # error_margin: Margin of error allowed + +# for String testcase: + # - test_case_type: stringtestcase + # correct: Exact string to be compared + # string_check: lower or exact.(case insensitive or sensitive) + +type: code +# mcq, Single Correct Choice, +# mcc, Multiple Correct Choices, +# code, Code Question, +# upload, Assignment Upload, +# integer, Answer in Integer, +# string, Answer in String, +# float, Answer in Float + +grade_assignment_upload: false +# Grade uploaded assignment (works with hook)true or false + +partial_grading: false +# partial grading with respect to each testcase. diff --git a/yaksh/fixtures/demo_questions.zip b/yaksh/fixtures/demo_questions.zip Binary files differindex c68e7ef..f9c5c2f 100644 --- a/yaksh/fixtures/demo_questions.zip +++ b/yaksh/fixtures/demo_questions.zip diff --git a/yaksh/models.py b/yaksh/models.py index 87e6260..fde203c 100644 --- a/yaksh/models.py +++ b/yaksh/models.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals from datetime import datetime, timedelta import json +import yaml from random import sample from collections import Counter from django.db import models @@ -26,6 +27,7 @@ from textwrap import dedent from .file_utils import extract_files, delete_files from yaksh.xmlrpc_clients import code_server from django.conf import settings +from django.forms.models import model_to_dict languages = ( @@ -389,43 +391,38 @@ class Question(models.Model): for question in questions: test_case = question.get_test_cases() file_names = question._add_and_get_files(zip_file) - q_dict = { - 'summary': question.summary, - 'description': question.description, - 'points': question.points, 'language': question.language, - 'type': question.type, 'active': question.active, - 'snippet': question.snippet, - 'testcase': [case.get_field_value() for case in test_case], - 'files': file_names - } + q_dict = model_to_dict(question, exclude=['id', 'user','tags']) + q_dict['testcase']= [case.get_field_value() for case in test_case] + q_dict['files'] = file_names + questions_dict.append(q_dict) - question._add_json_to_zip(zip_file, questions_dict) + question._add_yaml_to_zip(zip_file, questions_dict) return zip_file_name def load_questions(self, questions_list, user, file_path=None, files_list=None): try: - questions = json.loads(questions_list) - except ValueError as exc_msg: - msg = "Error Parsing Json: {0}".format(exc_msg) - return msg - for question in questions: - question['user'] = user - file_names = question.pop('files') - test_cases = question.pop('testcase') - que, result = Question.objects.get_or_create(**question) - if file_names: - que._add_files_to_db(file_names, file_path) - for test_case in test_cases: - test_case_type = test_case.pop('test_case_type') - model_class = get_model_class(test_case_type) - new_test_case, obj_create_status = \ - model_class.objects.get_or_create( - question=que, **test_case - ) + questions = yaml.safe_load_all(questions_list) + for question in questions: + question['user'] = user + file_names = question.pop('files') + test_cases = question.pop('testcase') + que, result = Question.objects.get_or_create(**question) + if file_names: + que._add_files_to_db(file_names, file_path) + for test_case in test_cases: + test_case_type = test_case.pop('test_case_type') + model_class = get_model_class(test_case_type) + new_test_case, obj_create_status = \ + model_class.objects.get_or_create( + question=que, **test_case + ) new_test_case.type = test_case_type new_test_case.save() - return "Questions Uploaded Successfully" + msg = "Questions Uploaded Successfully" + except yaml.scanner.ScannerError as exc_msg: + msg = "Error Parsing Yaml: {0}".format(exc_msg) + return msg def get_test_cases(self, **kwargs): tc_list = [] @@ -481,25 +478,24 @@ class Question(models.Model): file_upload.extract = extract file_upload.file.save(file_name, django_file, save=True) - def _add_json_to_zip(self, zip_file, q_dict): - json_data = json.dumps(q_dict, indent=2) + def _add_yaml_to_zip(self, zip_file, q_dict): tmp_file_path = tempfile.mkdtemp() - json_path = os.path.join(tmp_file_path, "questions_dump.json") - with open(json_path, "w") as json_file: - json_file.write(json_data) - zip_file.write(json_path, os.path.basename(json_path)) + yaml_path = os.path.join(tmp_file_path, "questions_dump.yaml") + with open(yaml_path, "w") as yaml_file: + yaml.safe_dump_all(q_dict, yaml_file, default_flow_style=False) + zip_file.write(yaml_path, os.path.basename(yaml_path)) zip_file.close() shutil.rmtree(tmp_file_path) - def read_json(self, file_path, user, files=None): - json_file = os.path.join(file_path, "questions_dump.json") + def read_yaml(self, file_path, user, files=None): + yaml_file = os.path.join(file_path, "questions_dump.yaml") msg = "" - if os.path.exists(json_file): - with open(json_file, 'r') as q_file: + if os.path.exists(yaml_file): + with open(yaml_file, 'r') as q_file: questions_list = q_file.read() msg = self.load_questions(questions_list, user, file_path, files) else: - msg = "Please upload zip file with questions_dump.json in it." + msg = "Please upload zip file with questions_dump.yaml in it." if files: delete_files(files, file_path) @@ -510,7 +506,7 @@ class Question(models.Model): settings.FIXTURE_DIRS, 'demo_questions.zip' ) files, extract_path = extract_files(zip_file_path) - self.read_json(extract_path, user, files) + self.read_yaml(extract_path, user, files) def __str__(self): return self.summary diff --git a/yaksh/static/yaksh/js/show_question.js b/yaksh/static/yaksh/js/show_question.js index e3ed1cc..7cfbf4c 100644 --- a/yaksh/static/yaksh/js/show_question.js +++ b/yaksh/static/yaksh/js/show_question.js @@ -37,3 +37,7 @@ function confirm_edit(frm) else return true; } +$(document).ready(function() + { + $("#questions-table").tablesorter({sortList: [[]]}); + });
\ No newline at end of file diff --git a/yaksh/templates/yaksh/showquestions.html b/yaksh/templates/yaksh/showquestions.html index a136ddf..78be301 100644 --- a/yaksh/templates/yaksh/showquestions.html +++ b/yaksh/templates/yaksh/showquestions.html @@ -2,31 +2,62 @@ {% block title %} Questions {% endblock %} -{% block pagetitle %} List of Questions {% endblock pagetitle %} +{% block pagetitle %} Questions {% endblock pagetitle %} {% block script %} <script src="{{ URL_ROOT }}/static/yaksh/js/show_question.js"></script> <script src="{{ URL_ROOT }}/static/yaksh/js/question_filter.js"></script> +<script src="{{ URL_ROOT }}/static/yaksh/js/jquery.tablesorter.min.js"></script> {% endblock %} {% block content %} - -<h4>Upload ZIP file for adding questions</h4> +<div class="row"> + <div class="col-sm-3 col-md-2 sidebar"> + <ul class="nav nav-sidebar nav-stacked"> + <li class="active"><a href="#show" data-toggle="pill" > Show all Questions</a></li> + <li><a href="#updown" data-toggle="pill" > Upload and Download Questions</a></li> + </ul> + </div> +<div class="tab-content"> +<!-- Upload Questions --> +<div id="updown" class="tab-pane fade"> +<a class="btn btn-primary" href="{{URL_ROOT}}/exam/manage/courses/download_yaml_template/"> Download Template</a> +<br/> +<h4> Or </h4> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} -{{ upload_form.as_p }} -<button class="btn btn-primary" type="submit" name="upload" value="upload"> -Upload File <span class="glyphicon glyphicon-open"></span></button> + {{ upload_form.as_p }} +<br/> +<h4> And </h4> +<button class="btn btn-success" type="submit" name="upload" value="upload"> +Upload File <span class="glyphicon glyphicon-open"/></button> </form> +</div> +<!-- End of upload questions --> + +<!-- Show questions --> +<div id="show" class= "tab-pane fade in active"> +<form name=frm action="" method="post"> +{% csrf_token %} {% if message %} -<h4>{{ message }}</h4> +{%if message == "Questions Uploaded Successfully"%} +<div class="alert alert-success alert-dismissable"> +<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> + {{ message }} +</div> +{%else %} +<div class="alert alert-danger alert-dismissable"> + <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> + {{ message }} +</div> +{% endif %} {% endif %} {% if msg %} -<h4>{{ msg }}</h4> +<div class="alert alert-danger alert-dismissable"> + <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> + {{ msg }} +</div> {% endif %} -<br><br> -<form name=frm action="" method="post"> -{% csrf_token %} <div class="row" id="selectors"> <h5 style="padding-left: 20px;">Filters</h5> <div class="col-md-3"> @@ -46,17 +77,46 @@ Upload File <span class="glyphicon glyphicon-open"></span></button> <div id="filtered-questions"> {% if questions %} <h5><input id="checkall" type="checkbox"> Select All </h5> + +<table id="questions-table" class="tablesorter table table table-striped"> + <thead> + <tr> + <th> Select </th> + <th> Summary </th> + <th> Language </th> + <th> Type </th> + <th> Marks </th> + </tr> + </thead> + <tbody> + {% for i in questions %} -<input type="checkbox" name="question" value="{{ i.id }}"> <a href="{{URL_ROOT}}/exam/manage/addquestion/{{ i.id }}">{{ i }}</a><br> +<tr> +<td> +<input type="checkbox" name="question" value="{{ i.id }}"> +</td> +<td><a href="{{URL_ROOT}}/exam/manage/addquestion/{{ i.id }}">{{i.summary|capfirst}}</a></td> +<td>{{i.language|capfirst}}</td> +<td>{{i.type|capfirst}}</td> +<td>{{i.points}}</td> +</tr> {% endfor %} +</tbody> +</table> {% endif %} </div> <br> +<center> <button class="btn btn-primary" type="button" onclick='location.replace("{{URL_ROOT}}/exam/manage/addquestion/");'>Add Question <span class="glyphicon glyphicon-plus"></span></button> {% if questions %} <button class="btn btn-primary" type="submit" name='download' value='download'>Download Selected <span class="glyphicon glyphicon-save"></span></button> <button class="btn btn-primary" type="submit" name="test" value="test">Test Selected</button> {% endif %} <button class="btn btn-danger" type="submit" onClick="return confirm_delete(frm);" name='delete' value='delete'>Delete Selected <span class="glyphicon glyphicon-minus"></span></button> +</center> </form> -{% endblock %} +</div> +</div> +</div> +<!-- End of Show questions --> +{% endblock %}
\ No newline at end of file diff --git a/yaksh/test_models.py b/yaksh/test_models.py index c86d9a3..8dc3244 100644 --- a/yaksh/test_models.py +++ b/yaksh/test_models.py @@ -3,6 +3,7 @@ from yaksh.models import User, Profile, Question, Quiz, QuestionPaper,\ QuestionSet, AnswerPaper, Answer, Course, StandardTestCase,\ StdIOBasedTestCase, FileUpload, McqTestCase, AssignmentUpload import json +import yaml from datetime import datetime, timedelta from django.utils import timezone import pytz @@ -111,7 +112,7 @@ class QuestionTestCases(unittest.TestCase): user=self.user1 ) - self.question2 = Question.objects.create(summary='Demo Json', + self.question2 = Question.objects.create(summary='Yaml Json', language='python', type='code', active=True, @@ -159,8 +160,8 @@ class QuestionTestCases(unittest.TestCase): "language": "Python", "type": "Code", "testcase": self.test_case_upload_data, "files": [[file1, 0]], - "summary": "Json Demo"}] - self.json_questions_data = json.dumps(questions_data) + "summary": "Yaml Demo"}] + self.yaml_questions_data = yaml.safe_dump_all(questions_data) def tearDown(self): shutil.rmtree(self.load_tmp_path) @@ -191,7 +192,7 @@ class QuestionTestCases(unittest.TestCase): self.assertIn(tag, ['python', 'function']) def test_dump_questions(self): - """ Test dump questions into json """ + """ Test dump questions into Yaml """ question = Question() question_id = [self.question2.id] questions_zip = question.dump_questions(question_id, self.user2) @@ -200,8 +201,8 @@ class QuestionTestCases(unittest.TestCase): tmp_path = tempfile.mkdtemp() zip_file.extractall(tmp_path) test_case = self.question2.get_test_cases() - with open("{0}/questions_dump.json".format(tmp_path), "r") as f: - questions = json.loads(f.read()) + with open("{0}/questions_dump.yaml".format(tmp_path), "r") as f: + questions = yaml.safe_load_all(f.read()) for q in questions: self.assertEqual(self.question2.summary, q['summary']) self.assertEqual(self.question2.language, q['language']) @@ -216,13 +217,13 @@ class QuestionTestCases(unittest.TestCase): os.remove(os.path.join(tmp_path, file)) def test_load_questions(self): - """ Test load questions into database from json """ + """ Test load questions into database from Yaml """ question = Question() - result = question.load_questions(self.json_questions_data, self.user1) - question_data = Question.objects.get(summary="Json Demo") + result = question.load_questions(self.yaml_questions_data, self.user1) + question_data = Question.objects.get(summary="Yaml Demo") file = FileUpload.objects.get(question=question_data) test_case = question_data.get_test_cases() - self.assertEqual(question_data.summary, 'Json Demo') + self.assertEqual(question_data.summary, 'Yaml Demo') self.assertEqual(question_data.language, 'Python') self.assertEqual(question_data.type, 'Code') self.assertEqual(question_data.description, 'factorial of a no') diff --git a/yaksh/test_views.py b/yaksh/test_views.py index ef222e2..e5308fc 100644 --- a/yaksh/test_views.py +++ b/yaksh/test_views.py @@ -2983,7 +2983,7 @@ class TestShowQuestions(TestCase): zip_file = string_io(response.content) zipped_file = zipfile.ZipFile(zip_file, 'r') self.assertIsNone(zipped_file.testzip()) - self.assertIn('questions_dump.json', zipped_file.namelist()) + self.assertIn('questions_dump.yaml', zipped_file.namelist()) zip_file.close() zipped_file.close() diff --git a/yaksh/urls.py b/yaksh/urls.py index 5270068..87ee655 100644 --- a/yaksh/urls.py +++ b/yaksh/urls.py @@ -105,5 +105,7 @@ urlpatterns = [ url(r'^manage/download/user_assignment/(?P<question_id>\d+)/(?P<user_id>\d+)/(?P<quiz_id>\d+)/$', views.download_assignment_file, name="download_user_assignment"), url(r'^manage/download/quiz_assignments/(?P<quiz_id>\d+)/$', - views.download_assignment_file, name="download_quiz_assignment") + views.download_assignment_file, name="download_quiz_assignment"), + url(r'^manage/courses/download_yaml_template/', + views.download_yaml_template, name="download_yaml_template"), ] diff --git a/yaksh/views.py b/yaksh/views.py index c10ba6a..68253bc 100644 --- a/yaksh/views.py +++ b/yaksh/views.py @@ -1015,7 +1015,7 @@ def show_all_questions(request): if file_name[-1] == "zip": ques = Question() files, extract_path = extract_files(questions_file) - context['message'] = ques.read_json(extract_path, user, + context['message'] = ques.read_yaml(extract_path, user, files) else: message = "Please Upload a ZIP file" @@ -1590,3 +1590,20 @@ def duplicate_course(request, course_id): 'instructor/administrator.' return complete(request, msg, attempt_num=None, questionpaper_id=None) return my_redirect('/exam/manage/courses/') + +@login_required +@email_verified +def download_yaml_template(request): + user = request.user + if not is_moderator(user): + raise Http404('You are not allowed to view this page!') + template_path = os.path.join(os.path.dirname(__file__), "demo_templates", + "yaml_question_template" + ) + with open(template_path, 'r') as f: + yaml_str = f.read() + response = HttpResponse(yaml_str, content_type='text/yaml') + response['Content-Disposition'] = 'attachment; filename="questions_dump.yaml"' + + return response + |