Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use serializier from djangorestframework for api. #723

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 40 additions & 75 deletions course/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,19 @@
THE SOFTWARE.
"""

from django import http
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404

from course.auth import with_course_api_auth, APIError
from course.constants import (
participation_permission as pperm,
)
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from course.auth import with_course_api_auth, APIError
from course.models import FlowSession
from course.constants import participation_permission as pperm
from course.serializers import (
FlowSessionSerializer, FlowPageDateSerializer, FlowPageVisitSerializer,
FlowPageVisitGradeSerializer)

# {{{ mypy

Expand All @@ -44,45 +47,17 @@
# }}}


def flow_session_to_json(sess):
# type: (FlowSession) -> Any
last_activity = sess.last_activity()
return dict(
id=sess.id,
participation_username=(
sess.participation.user.username
if sess.participation is not None
else None),
participation_institutional_id=(
sess.participation.user.institutional_id
if sess.participation is not None
else None),
active_git_commit_sha=sess.active_git_commit_sha,
flow_id=sess.flow_id,

start_time=sess.start_time.isoformat(),
completion_time=sess.completion_time,
last_activity_time=(
last_activity.isoformat()
if last_activity is not None
else None),
page_count=sess.page_count,

in_progress=sess.in_progress,
access_rules_tag=sess.access_rules_tag,
expiration_mode=sess.expiration_mode,
points=sess.points,
max_points=sess.max_points,
result_comment=sess.result_comment,
)


@api_view(["GET"])
@with_course_api_auth("Token")
def get_flow_sessions(api_ctx, course_identifier):
# type: (APIContext, Text) -> http.HttpResponse
# type: (APIContext, Text) -> Response

if not api_ctx.has_permission(pperm.view_gradebook):
raise PermissionDenied("token role does not have required permissions")
return Response(
exception=PermissionDenied(
"token role does not have required permissions"),
status=status.HTTP_403_FORBIDDEN
)

try:
flow_id = api_ctx.request.GET["flow_id"]
Expand All @@ -93,17 +68,22 @@ def get_flow_sessions(api_ctx, course_identifier):
course=api_ctx.course,
flow_id=flow_id)

result = [flow_session_to_json(sess) for sess in sessions]
result = [FlowSessionSerializer(sess).data for sess in sessions]

return http.JsonResponse(result, safe=False)
return Response(result)


@api_view(["GET"])
@with_course_api_auth("Token")
def get_flow_session_content(api_ctx, course_identifier):
# type: (APIContext, Text) -> http.HttpResponse
# type: (APIContext, Text) -> Response

if not api_ctx.has_permission(pperm.view_gradebook):
raise PermissionDenied("token role does not have required permissions")
return Response(
exception=PermissionDenied(
"token role does not have required permissions"),
status=status.HTTP_403_FORBIDDEN
)

try:
session_id_str = api_ctx.request.GET["flow_session_id"]
Expand All @@ -115,8 +95,11 @@ def get_flow_session_content(api_ctx, course_identifier):
flow_session = get_object_or_404(FlowSession, id=session_id)

if flow_session.course != api_ctx.course:
raise PermissionDenied(
"session's course does not match auth context")
return Response(
exception=PermissionDenied(
"session's course does not match auth context"),
status=status.HTTP_403_FORBIDDEN
)

from course.content import get_course_repo
from course.flow import adjust_flow_session_page_data, assemble_answer_visits
Expand All @@ -138,15 +121,7 @@ def get_flow_session_content(api_ctx, course_identifier):

assert i == page_data.page_ordinal

page_data_json = dict(
ordinal=i,
page_type=page_data.page_type,
group_id=page_data.group_id,
page_id=page_data.page_id,
page_data=page_data.data,
title=page_data.title,
bookmarked=page_data.bookmarked,
)
page_data_json = FlowPageDateSerializer(page_data).data
answer_json = None
grade_json = None

Expand Down Expand Up @@ -174,27 +149,17 @@ def get_flow_session_content(api_ctx, course_identifier):
norm_answer = [answer_file_ext,
b64encode(norm_bytes_answer).decode("utf-8")]

answer_json = dict(
visit_time=visit.visit_time.isoformat(),
remote_address=repr(visit.remote_address),
user=visit.user.username if visit.user is not None else None,
impersonated_by=(visit.impersonated_by.username
if visit.impersonated_by is not None else None),
is_synthetic_visit=visit.is_synthetic,
answer_data=visit.answer,
answer=norm_answer,
)
answer_json = FlowPageVisitSerializer(visit).data
answer_json.pop("flow_session")
answer_json.pop("page_data")
if norm_answer is not None:
answer_json["norm_answer"] = norm_answer

grade = visit.get_most_recent_grade()
if grade is not None:
grade_json = dict(
grader=(grade.grader.username
if grade.grader is not None else None),
grade_time=grade.grade_time.isoformat(),
graded_at_git_commit_sha=grade.graded_at_git_commit_sha,
max_points=grade.max_points,
correctness=grade.correctness,
feedback=grade.feedback)
grade_json = FlowPageVisitGradeSerializer(grade).data
grade_json.pop("visit")
grade_json.pop("grade_data")

pages.append({
"page": page_data_json,
Expand All @@ -203,11 +168,11 @@ def get_flow_session_content(api_ctx, course_identifier):
})

result = {
"session": flow_session_to_json(flow_session),
"session": FlowSessionSerializer(flow_session).data,
"pages": pages,
}

return http.JsonResponse(result, safe=False)
return Response(result)


# vim: foldmethod=marker
135 changes: 135 additions & 0 deletions course/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# -*- coding: utf-8 -*-

from __future__ import division

__copyright__ = "Copyright (C) 2020 Dong Zhuang"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


from rest_framework import serializers
from course.models import (
FlowSession, FlowPageVisit, FlowPageData, FlowPageVisitGrade)


class FlowSessionSerializer(serializers.ModelSerializer):

class Meta:
model = FlowSession

fields = ("id",
"username",
"institutional_id",
"active_git_commit_sha",
"flow_id",
"start_time",
"completion_time",
"last_activity",
"page_count",
"in_progress",
"access_rules_tag",
"expiration_mode",
"points",
"max_points",
"result_comment",
"points_percentage",
)

username = serializers.CharField(
source="participation.user.username", read_only=True)

institutional_id = serializers.CharField(
source="participation.user.institutional_id", read_only=True)

last_activity = serializers.SerializerMethodField()

points_percentage = serializers.SerializerMethodField()

def get_last_activity(self, obj):
return obj.last_activity()

def get_points_percentage(self, obj):
return obj.points_percentage()


class FlowPageDateSerializer(serializers.ModelSerializer):

class Meta:
model = FlowPageData

fields = ("page_ordinal",
"page_type",
"group_id",
"page_id",
"data",
"title",
"bookmarked"
)


class FlowPageVisitSerializer(serializers.ModelSerializer):

class Meta:
model = FlowPageVisit

fields = ("flow_session",
"page_data",
"visit_time",
"remote_address",
"user",
"impersonated_by",
"is_synthetic",
"answer",
"is_submitted_answer",
)

user = serializers.CharField(source="visitor.username", read_only=True)
impersonated_by = serializers.CharField(
source="impersonated_by.user.username", read_only=True)


class FlowPageVisitGradeSerializer(serializers.ModelSerializer):

class Meta:
model = FlowPageVisitGrade

fields = (
"visit",
"grader",
"grade_time",
"graded_at_git_commit_sha",
"grade_data",
"max_points",
"correctness",
"feedback",
"percentage",
)

grader = serializers.CharField(
source="grader.username", read_only=True)

percentage = serializers.SerializerMethodField()

def get_percentage(self, obj):
if obj.correctness is not None:
return 100 * obj.correctness
else:
return None
Comment on lines +131 to +135
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to make this a read-only property on the FlowPageVisitGrade class instead of the serializer?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your review. What's your opinion? @inducer

17 changes: 16 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ nbconvert = "^5.2.1"
IPython = "^7.15.0"
# For relate script
colorama = "*"
djangorestframework = "^3.11.0"

[tool.poetry.dev-dependencies]
codecov = "^2.1.4"
Expand Down
Loading