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

Removed possible infinite loop in INBUS integration #467

Merged
merged 2 commits into from
Apr 16, 2024
Merged
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
5 changes: 3 additions & 2 deletions api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import common.bulk_import
from common.bulk_import import ImportException
from common import inbus
from common.inbus import inbus
from pathlib import Path
from shutil import copytree, ignore_patterns
from django.utils.dateparse import parse_datetime
Expand All @@ -33,7 +33,7 @@
@user_passes_test(is_teacher)
def tasks_list(request):
result = []
for task in Task.objects.all():

Check failure on line 36 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[Task]"   Member "objects" is unknown (reportAttributeAccessIssue)
result.append({
'id': task.pk,
'title': task.name,
Expand Down Expand Up @@ -176,7 +176,7 @@
"""
Returns list of all subjects.
"""
subjects = Subject.objects.all()

Check failure on line 179 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[Subject]"   Member "objects" is unknown (reportAttributeAccessIssue)
subjects_dicts = [ s.as_dict() for s in subjects ]

resp = {'subjects': subjects_dicts}
Expand Down Expand Up @@ -221,7 +221,7 @@
user = None
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:

Check failure on line 224 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "DoesNotExist" for type "type[User]"   Member "DoesNotExist" is unknown (reportAttributeAccessIssue)
person_inbus = inbus_search_user(username)
if person_inbus:
user = user_from_inbus_person(person_inbus)
Expand Down Expand Up @@ -257,15 +257,15 @@
def set_subject(task):
subj = data['path'].split('/')[0]
try:
task.subject = Subject.objects.get(abbr=subj)

Check failure on line 260 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[Subject]"   Member "objects" is unknown (reportAttributeAccessIssue)
return None
except Subject.DoesNotExist:

Check failure on line 262 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "DoesNotExist" for type "type[Subject]"   Member "DoesNotExist" is unknown (reportAttributeAccessIssue)
return JsonResponse({
'errors': [f'Subject "{subj}" does not exist! Please set correct subject abbr in the path.'],
}, status=400)

if not task_id:
if Task.objects.filter(code=data['path']).count() != 0:

Check failure on line 268 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[Task]"   Member "objects" is unknown (reportAttributeAccessIssue)
return JsonResponse({
'errors': [f'The task with path "{data["path"]}" already exists.'],
}, status=400)
Expand All @@ -282,7 +282,7 @@
'errors': [f'Cannot create task in the directory "{data["path"]}", because there already exists these tasks:\n{chr(10).join(paths)}'],
}, status=400)
else:
task = Task.objects.get(id=task_id)

Check failure on line 285 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[Task]"   Member "objects" is unknown (reportAttributeAccessIssue)

err = set_subject(task)
if err:
Expand All @@ -303,7 +303,7 @@
except FileNotFoundError as e:
logger.warn(e)

for assignment in AssignedTask.objects.filter(task_id=task.pk):

Check failure on line 306 in api/views.py

View workflow job for this annotation

GitHub Actions / pyright

Cannot access member "objects" for type "type[AssignedTask]"   Member "objects" is unknown (reportAttributeAccessIssue)
try:
os.renames(
os.path.join("submits", *submit_assignment_path(assignment), task.code),
Expand Down Expand Up @@ -608,7 +608,8 @@
subject = post['subject']
activities_id = post['activities']

activities = [ inbus.inbus.concrete_activity(activity_id) for activity_id in activities_id ]
activities = [inbus.concrete_activity(activity_id) for activity_id in activities_id]
activities = [concrete_activity for concrete_activity in activities if concrete_activity is not None]
semester = Semester.objects.get(pk=semester_id)

try:
Expand Down
70 changes: 44 additions & 26 deletions common/inbus/inbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,50 @@ def person_by_login(login: str) -> dto.PersonSimple | None:
if 'login' not in person_json:
return None

person_simple = dto.PersonSimple(login=person_json["login"].upper(), first_name=person_json.get('firstName', ''), second_name=person_json.get('secondName', ''),
person_simple = dto.PersonSimple(login=person_json["login"].upper(), first_name=person_json.get('firstName', ''),
second_name=person_json.get('secondName', ''),
full_name=person_json.get('fullName', ''), email=person_json.get('email', ''))

return person_simple


def subject_versions(department_id: dto.DepartmentId = 386) -> List[dto.SubjectVersion]:
def subject_versions(department_id: dto.DepartmentId = dto.DepartmentId(386)) -> List[dto.SubjectVersion]:
"""
Get list of all subjects and their versions by department.
Here `386` is Department of Computer Science.
"""
results_per_page = 20
results_per_page: int = 20
subject_versions = []
offset = 0
offset: int = 0
while True:
url = urllib.parse.urljoin(config.INBUS_SERVICE_EDISON_URL, 'edu/subjectVersions')
subject_versions_resp = utils.inbus_request(url, {'departmentId': department_id, 'offset': offset, 'limit': results_per_page})

subject_versions_json = subject_versions_resp.json()
if subject_versions_resp:
subject_versions_json = subject_versions_resp.json()

for subject_version_json in subject_versions_json:
subject_json = subject_version_json['subject']
subject_guarantee = serde.from_dict(dto.Person, subject_json['guarantee'])
subject_version_guarantee = serde.from_dict(dto.Person, subject_version_json['guarantee'])
subject = dto.Subject(subjectId=subject_json['subjectId'], code=subject_json['code'], abbrev=subject_json['abbrev'],
title=subject_json['title'], guarantee=subject_guarantee)
subject_version = dto.SubjectVersion(subjectVersionId=subject_version_json['subjectVersionId'], subject=subject,
subjectVersionCompleteCode=subject_version_json['subjectVersionCompleteCode'], guarantee=subject_version_guarantee)
for subject_version_json in subject_versions_json:
subject_json = subject_version_json['subject']
subject_guarantee = serde.from_dict(dto.Person, subject_json['guarantee'])
subject_version_guarantee = serde.from_dict(dto.Person, subject_version_json['guarantee'])
subject = dto.Subject(subjectId=subject_json['subjectId'], code=subject_json['code'],
abbrev=subject_json['abbrev'], title=subject_json['title'],
guarantee=subject_guarantee)
subject_version = dto.SubjectVersion(subjectVersionId=subject_version_json['subjectVersionId'],
subject=subject,
subjectVersionCompleteCode=subject_version_json['subjectVersionCompleteCode'],
guarantee=subject_version_guarantee)

subject_versions.append(subject_version)
subject_versions.append(subject_version)

results = len(subject_versions_json)
results = len(subject_versions_json)

offset += results
offset += results

if results == 0:
if results == 0:
break

else:
break

return subject_versions
Expand All @@ -69,29 +77,39 @@ def schedule_subject_by_version_id(subject_version_id: dto.SubjectVersionId) ->
url = urllib.parse.urljoin(config.INBUS_SERVICE_EDISON_URL, 'schedule')
concrete_activities_resp = utils.inbus_request(url, {'subjectVersionId': subject_version_id, 'semesterId': 129})

concrete_activities_json = concrete_activities_resp.json()
concrete_activities = []

if concrete_activities_resp:
concrete_activities_json = concrete_activities_resp.json()

concrete_activities = [ serde.from_dict(dto.ConcreteActivity, concrete_activity_dict) for concrete_activity_dict in concrete_activities_json ]
concrete_activities = [ serde.from_dict(dto.ConcreteActivity, concrete_activity_dict) for concrete_activity_dict in concrete_activities_json ]

return concrete_activities
return dto.SubjectVersionSchedule(concrete_activities)


def concrete_activity(concrete_activity_id: dto.ConcreteActivityId) -> dto.ConcreteActivity:
def concrete_activity(concrete_activity_id: dto.ConcreteActivityId) -> dto.ConcreteActivity | None:
url = urllib.parse.urljoin(config.INBUS_SERVICE_EDISON_URL, f'schedule/{concrete_activity_id}')
concrete_activity_resp = utils.inbus_request(url, {})
concrete_activity_json = concrete_activity_resp.json()

concrete_activity = serde.from_dict(dto.ConcreteActivity, concrete_activity_json)
if concrete_activity_resp:
concrete_activity_json = concrete_activity_resp.json()

return concrete_activity
concrete_activity: dto.ConcreteActivity = serde.from_dict(dto.ConcreteActivity, concrete_activity_json)
return concrete_activity
else:
return None


def students_in_concrete_activity(concrete_activity_id: dto.ConcreteActivityId) -> List[dto.StudyRelation]:
url = urllib.parse.urljoin(config.INBUS_SERVICE_EDISON_URL, f'schedule/{concrete_activity_id}/studyRelations')
study_relation_resp = utils.inbus_request(url, {})
study_relation_json = study_relation_resp.json()

study_relations = [ serde.from_dict(dto.StudyRelation, study_relation) for study_relation in study_relation_json ]
study_relations: List[dto.StudyRelation] = []

if study_relation_resp:
study_relation_json = study_relation_resp.json()

study_relations = [serde.from_dict(dto.StudyRelation, study_relation) for study_relation in study_relation_json]

return study_relations

Expand Down
2 changes: 1 addition & 1 deletion common/inbus/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def is_response_ok_or_new_token_(response: requests.Response) -> bool:
return False


def inbus_request(url, params: Dict = None) -> requests.Response | None:
def inbus_request(url, params: Dict | None = None) -> requests.Response | None:
if params is None:
params = {}
token = inbus_token()
Expand Down
Loading