Пример #1
0
def send_student_assignment(req, assignment_hash, teacher, group, assignment):

    try:
        data = json.loads(req.body)
    except ValueError:
        return response_400(req, msg=_("Wrong data type was sent."))

    try:
        email = data["email"]
    except KeyError:
        return response_400(req, msg=_("There are missing parameters."))

    try:
        student = Student.objects.get(student__email=email)
    except Student.DoesNotExist:
        return response_400(
            req, msg=_('There is no student with email "{}".'.format(email)))

    student_assignment, __ = StudentAssignment.objects.get_or_create(
        group_assignment=assignment, student=student)

    err = student_assignment.send_email("new_assignment")

    if err is not None:
        return response_500(req, msg=_(err))

    return HttpResponse()
Пример #2
0
def test_response_500__default_message(rf, caplog):
    logger = logging.getLogger("test")
    req = rf.get("/test")
    req.user = AnonymousUser()

    resp = response_500(req,
                        msg="test1",
                        log=logger.warning,
                        use_template=True)

    assert isinstance(resp, TemplateResponse)
    assert resp.status_code == 500
    assert len(caplog.records) == 1
    assert (caplog.records[0].message ==
            "500 error for user AnonymousUser on path /test.")
Пример #3
0
def test_response_500(rf, caplog):
    logger = logging.getLogger("test")
    req = rf.get("/test")

    resp = response_500(
        req,
        msg="test1",
        logger_msg="test2",
        log=logger.warning,
        use_template=True,
    )

    assert isinstance(resp, TemplateResponse)
    assert resp.status_code == 500
    assert len(caplog.records) == 1
    assert caplog.records[0].message == "test2"
Пример #4
0
def get_gradebook_task_result(req, teacher):
    """
    Returns a 200 response if the gradebook is ready. If not, will return a 202
    response.

    Parameters
    ----------
    req : HttpRequest
        Request with:
            parameters:
                task_id: str
                    Id of the celery task responsible for the gradebook
                    generation sent with the first request for a gradebook
    teacher : Teacher
        Teacher instance returned by `teacher_required` (not used)

    Returns
    -------
    HttpResponse
        Either
            Empty 200 response (task done)
            Empty 202 response (accepted, still processing)
            Empty 500 response (error)
    """
    args = get_json_params(req, args=["task_id"])
    if isinstance(args, HttpResponse):
        return args
    (task_id, ), _ = args

    result = AsyncResult(task_id)

    try:
        if result.ready():
            return HttpResponse("", status=200)
        else:
            return HttpResponse("", status=202)
    except AttributeError:
        return response_500(
            req,
            msg="",
            logger_msg="Error computing gradebook for teacher {}".format(
                teacher.user.username) + " and task {}.".format(task_id),
            log=logger.warning,
            use_template=False,
        )
Пример #5
0
def download_gradebook(req, teacher, results=None):
    """
    Download the wanted gradebook.

    Parameters
    ----------
    req : HttpRequest
        Request with:
            parameters:
                task_id: str
                    Id of the celery task responsible for the gradebook
                    generation sent with the first request for a gradebook
    teacher : Teacher
        Teacher instance returned by `teacher_required` (not used)
    results : Optional[Dict[str, Any]]
        Either
            If group gradebook
                {
                    group: str
                        Title of the group
                    assignments: List[str]
                        Assignment identifier
                    school_id_needed: bool
                        If a school id is needed
                    results: [{
                        school_id: Optional[str]
                            School id if needed
                        email: str
                            Student email
                        assignments: [{
                            n_completed: Optional[int]
                                Number of completed questions
                            n_correct: Optional[int]
                                Number of correct questions
                        }]
                    }]
                }
            If assignment gradebook
                {
                    group: str
                        Title of the group
                    assignment: str
                        Title of the assignment
                    questions: List[str]
                        Question title
                    school_id_needed: bool
                        If a school id is needed
                    results: [{
                        school_id: Optional[str]
                            School id if needed
                        email: str
                            Student email
                        questions: List[Optional[float]]
                            Grade for each question
                    }]
                }

    Returns
    -------
    StreamingHttpResponse
        csv file with the gradebook results
    """
    if results is None:
        args = get_json_params(req, args=["task_id"])
        if isinstance(args, HttpResponse):
            return args
        (task_id, ), _ = args

        result = AsyncResult(task_id)

        try:
            if not result.ready():
                return response_400(
                    req,
                    msg="The gradebook isn't ready.",
                    logger_msg="Not completed gradebook {}".format(task_id) +
                    " accessed by teacher {}".format(teacher.user.username),
                )
        except AttributeError:
            return response_500(
                req,
                msg="There is no gradebook corresponding to this url. "
                "Please ask for a new one.",
                logger_msg="Celery error getting gradebook"
                " for teacher {}".format(teacher.user.username) +
                " and task {}.".format(task_id),
                log=logger.warning,
                use_template=False,
            )

        results = result.result

        if RunningTask.objects.filter(id=task_id):
            RunningTask.objects.get(id=task_id).delete()

    if "assignment" in results:
        filename = "myDALITE_gradebook_{}_{}.csv".format(
            results["group"], results["assignment"])
    else:
        filename = "myDALITE_gradebook_{}.csv".format(results["group"])
    gradebook_gen = convert_gradebook_to_csv(results)
    data = chain(iter((filename + "\n", )), gradebook_gen)
    resp = StreamingHttpResponse(data, content_type="text/csv")
    return resp