def get_course_item_submissions(course_id, item_id, item_type, read_replica=True): submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related( 'student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, student_item__item_id=item_id, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest if (not latest_score.is_hidden() ) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield (StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score)
def get_submissions(student_item_dict, limit=None): """Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem this submission is associated with, as defined by a course, student, and item. limit (int): Optional parameter for limiting the returned number of submissions associated with this student item. If not specified, all associated submissions are returned. Returns: List dict: A list of dicts for the associated student item. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when the associated student item fails validation. SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> get_submissions(student_item_dict, 3) [{ 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' }] """ student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError as error: error_message = ("Error getting submission request for student item {}" .format(student_item_dict)) logger.exception(error_message) raise SubmissionNotFoundError(error_message) from error if limit: submission_models = submission_models[:limit] return SubmissionSerializer(submission_models, many=True).data
def get_all_course_submission_information(course_id, item_type, read_replica=True): """ For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (str): The course that we are getting submissions from. item_type (str): The type of items that we are getting submissions for. read_replica (bool): Try to use the database's read replica if it's available. Yields: A tuple of three dictionaries representing: (1) a student item with the following fields: student_id course_id student_item item_type (2) a submission with the following fields: student_item attempt_number submitted_at created_at answer (3) a score with the following fields, if one exists and it is the latest score: (if both conditions are not met, an empty dict is returned here) student_item submission points_earned points_possible created_at submission_uuid """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related( 'student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).iterator() for submission in query: student_item = submission.student_item serialized_score = {} if hasattr(student_item, 'scoresummary'): latest_score = student_item.scoresummary.latest # Only include the score if it is not a reset score (is_hidden), and if the current submission is the same # as the student_item's latest score's submission. This matches the behavior of the API's get_score method. if (not latest_score.is_hidden() ) and latest_score.submission.uuid == submission.uuid: serialized_score = ScoreSerializer(latest_score).data yield (StudentItemSerializer(student_item).data, SubmissionSerializer(submission).data, serialized_score)
def get_submission(submission_uuid): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, basestring): raise SubmissionRequestError( "submission_uuid ({!r}) must be a string type".format( submission_uuid)) cache_key = "submissions.submission.{}".format(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception as ex: # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception( "Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission {} (cached)".format(submission_uuid)) return cached_submission_data try: submission = Submission.objects.get(uuid=submission_uuid) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist: logger.error("Submission {} not found.".format(submission_uuid)) raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid)) except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = "Could not get submission due to error: {}".format(exc) logger.exception(err_msg) raise SubmissionInternalError(err_msg) logger.info("Get submission {}".format(submission_uuid)) return submission_data
def get_all_submissions(course_id, item_id, item_type, read_replica=True): """For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the submissions by. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Yields: Dicts representing the submissions with the following fields: student_item student_id attempt_number submitted_at created_at answer Raises: Cannot fail unless there's a database error, but may return an empty iterable. """ submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_id and primary key, so the reults will be grouped be grouped by # student, with the most recent submission being the first one in each group. query = submission_qs.select_related('student_item').filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, ).order_by('student_item__student_id', '-submitted_at', '-id').iterator() for unused_student_id, row_iter in itertools.groupby( query, operator.attrgetter('student_item.student_id')): submission = next(row_iter) # pylint: disable= stop-iteration-return data = SubmissionSerializer(submission).data data['student_id'] = submission.student_item.student_id yield data
def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. In general, users of top submissions can tolerate some latency in the search results, so by default this call uses a cache and the read replica (if available). Args: course_id (str): The course to retrieve for the top scores item_id (str): The item within the course to retrieve for the top scores item_type (str): The type of item to retrieve number_of_top_scores (int): The number of scores to return, greater than 0 and no more than 100. Kwargs: use_cache (bool): If true, check the cache before retrieving querying the database. read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: topscores (dict): The top scores for the assessment for the student item. An empty array if there are no scores or all scores are 0. Raises: SubmissionNotFoundError: Raised when a submission cannot be found for the associated student item. SubmissionRequestError: Raised when the number of top scores is higher than the MAX_TOP_SUBMISSIONS constant. Examples: >>> course_id = "TestCourse" >>> item_id = "u_67" >>> item_type = "openassessment" >>> number_of_top_scores = 10 >>> >>> get_top_submissions(course_id, item_id, item_type, number_of_top_scores) [{ 'score': 20, 'content': "Platypus" },{ 'score': 16, 'content': "Frog" }] """ if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( f"Number of top scores must be a number between 1 and {MAX_TOP_SUBMISSIONS}." ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First check the cache (unless caching is disabled) cache_key = "submissions.top_submissions.{course}.{item}.{type}.{number}".format( course=course_id, item=item_id, type=item_type, number=number_of_top_scores) top_submissions = cache.get(cache_key) if use_cache else None # If we can't find it in the cache (or caching is disabled), check the database # By default, prefer the read-replica. if top_submissions is None: try: query = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__item_id=item_id, student_item__item_type=item_type, latest__points_earned__gt=0).select_related( 'latest', 'latest__submission').order_by("-latest__points_earned") if read_replica: query = _use_read_replica(query) score_summaries = query[:number_of_top_scores] except DatabaseError as error: msg = "Could not fetch top score summaries for course {}, item {} of type {}".format( course_id, item_id, item_type) logger.exception(msg) raise SubmissionInternalError(msg) from error # Retrieve the submission content for each top score top_submissions = [{ "score": score_summary.latest.points_earned, "content": SubmissionSerializer( score_summary.latest.submission).data['answer'] } for score_summary in score_summaries] # Always store the retrieved list in the cache cache.set(cache_key, top_submissions, TOP_SUBMISSIONS_CACHE_TIMEOUT) return top_submissions
def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None, team_submission=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: first_submission = None attempt_number = 1 try: first_submission = Submission.objects.filter( student_item=student_item_model).first() except DatabaseError as error: error_message = "An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) from error if first_submission: attempt_number = first_submission.attempt_number + 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at if team_submission: model_kwargs["team_submission_uuid"] = team_submission.uuid try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError( field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except DatabaseError as error: error_message = "An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) from error
def get_submission(submission_uuid, read_replica=False): """Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError: Raised if the submission does not exist. SubmissionRequestError: Raised if the search parameter is not a string. SubmissionInternalError: Raised for unknown errors. Examples: >>> get_submission("20b78e0f32df805d21064fc912f40e9ae5ab260d") { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 23, 14, 52, 649284, tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ if not isinstance(submission_uuid, str): if isinstance(submission_uuid, UUID): submission_uuid = str(submission_uuid) else: raise SubmissionRequestError( msg= f"submission_uuid ({submission_uuid!r}) must be serializable") cache_key = Submission.get_cache_key(submission_uuid) try: cached_submission_data = cache.get(cache_key) except Exception: # pylint: disable=broad-except # The cache backend could raise an exception # (for example, memcache keys that contain spaces) logger.exception( "Error occurred while retrieving submission from the cache") cached_submission_data = None if cached_submission_data: logger.info("Get submission %s (cached)", submission_uuid) return cached_submission_data try: submission = _get_submission_model(submission_uuid, read_replica) submission_data = SubmissionSerializer(submission).data cache.set(cache_key, submission_data) except Submission.DoesNotExist as error: logger.error("Submission %s not found.", submission_uuid) raise SubmissionNotFoundError( f"No submission matching uuid {submission_uuid}") from error except Exception as exc: # Something very unexpected has just happened (like DB misconfig) err_msg = f"Could not get submission due to error: {exc}" logger.exception(err_msg) raise SubmissionInternalError(err_msg) from exc logger.info("Get submission %s", submission_uuid) return submission_data
def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None): """Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. answer (JSON-serializable): The answer given by the student to be assessed. submitted_at (datetime): The date in which this submission was submitted. If not specified, defaults to the current date. attempt_number (int): A student may be able to submit multiple attempts per question. This allows the designated attempt to be overridden. If the attempt is not specified, it will take the most recent submission, as specified by the submitted_at time, and use its attempt_number plus one. Returns: dict: A representation of the created Submission. The submission contains five attributes: student_item, attempt_number, submitted_at, created_at, and answer. 'student_item' is the ID of the related student item for the submission. 'attempt_number' is the attempt this submission represents for this question. 'submitted_at' represents the time this submission was submitted, which can be configured, versus the 'created_at' date, which is when the submission is first created. Raises: SubmissionRequestError: Raised when there are validation errors for the student item or submission. This can be caused by the student item missing required values, the submission being too long, the attempt_number is negative, or the given submitted_at time is invalid. SubmissionInternalError: Raised when submission access causes an internal error. Examples: >>> student_item_dict = dict( >>> student_id="Tim", >>> item_id="item_1", >>> course_id="course_1", >>> item_type="type_one" >>> ) >>> create_submission(student_item_dict, "The answer is 42.", datetime.utcnow, 1) { 'student_item': 2, 'attempt_number': 1, 'submitted_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 649284 tzinfo=<UTC>), 'created_at': datetime.datetime(2014, 1, 29, 17, 14, 52, 668850, tzinfo=<UTC>), 'answer': u'The answer is 42.' } """ student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering submissions for student item: {}".format( student_item_dict) logger.exception(error_message) raise SubmissionInternalError(error_message) attempt_number = submissions[0].attempt_number + 1 if submissions else 1 model_kwargs = { "student_item": student_item_model.pk, "answer": answer, "attempt_number": attempt_number, } if submitted_at: model_kwargs["submitted_at"] = submitted_at try: submission_serializer = SubmissionSerializer(data=model_kwargs) if not submission_serializer.is_valid(): raise SubmissionRequestError(field_errors=submission_serializer.errors) submission_serializer.save() sub_data = submission_serializer.data _log_submission(sub_data, student_item_dict) return sub_data except JsonFieldError: error_message = u"Could not serialize JSON field in submission {} for student item {}".format( model_kwargs, student_item_dict ) raise SubmissionRequestError(msg=error_message) except DatabaseError: error_message = u"An error occurred while creating submission {} for student item: {}".format( model_kwargs, student_item_dict ) logger.exception(error_message) raise SubmissionInternalError(error_message)
def _update_status(self, new_status): submission = self.get_object() submission.status = new_status submission.save() return Response(SubmissionSerializer(submission).data)
def list(self, request): submissions = request.user.submissions return Response(SubmissionSerializer(submissions, many=True).data)
def get(self, request, format=None): tasks = Submission.objects.all() serializer = SubmissionSerializer(tasks, many=True) return Response(serializer.data)
def post(self, request, format=None): serializer = SubmissionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register(self, request, pk=None): submission = Submission.objects.create(request.user, self.get_object()) expand_params = self.request.query_params.get('expand', None); return Response(SubmissionSerializer(submission, expand=expand_params).data)