Release - Upload
This commit is contained in:
@@ -0,0 +1,576 @@
|
||||
import datetime
|
||||
import inspect
|
||||
import json
|
||||
from rest_framework import serializers
|
||||
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
|
||||
from pruefplan_parser.models import JsonParser
|
||||
from pruefplan_viewer.models import *
|
||||
# from django.utils.encoding import smart_str
|
||||
|
||||
# Class to generate a UserToken with custom fields
|
||||
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
|
||||
@classmethod
|
||||
def get_token(cls, user):
|
||||
token = super().get_token(user) # Default Token
|
||||
|
||||
# Add custom informations to the Token
|
||||
token["username"] = user.username
|
||||
token["password"] = user.password
|
||||
|
||||
return token
|
||||
|
||||
|
||||
class API_ExamDataSet_ForStudentSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = API_ExamDataSet_ForStudent
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
|
||||
class PruefPlan_JSON_Serializer(serializers.Serializer):
|
||||
def create(self, validated_data):
|
||||
return super().create(validated_data)
|
||||
|
||||
def validate(self, data):
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"Das 'array'-Feld ist erforderlich und muss als Python-Liste verfügbar sein."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]} # Rückgabe des validierten Datenarrays
|
||||
|
||||
|
||||
class Lecturer_JSON_Serializer(serializers.Serializer):
|
||||
# Definiert die Felder, die der Serializer erwartet
|
||||
revision = serializers.CharField(required=True)
|
||||
array = serializers.ListField()
|
||||
|
||||
def create(self, validated_data):
|
||||
# Definieren der erwarteten Schlüssel im JSON-Daten
|
||||
idKey = "kennung"
|
||||
firstNameKey = "vorname"
|
||||
lastNameKey = "nachname"
|
||||
titleKey = "titel"
|
||||
|
||||
|
||||
created_lecturers = [] # Liste zum Speichern der erstellten Lecturer-Objekte
|
||||
try:
|
||||
# Schleife über die Daten, um Lecturer-Objekte zu erstellen
|
||||
for iteration_number, d in enumerate(validated_data["dataArray"]):
|
||||
# Lecturer-Objekt erstellen und speichern
|
||||
entry = Lecturer(
|
||||
identification=d[idKey],
|
||||
firstName=d[firstNameKey],
|
||||
lastName=d[lastNameKey],
|
||||
title=d[titleKey],
|
||||
|
||||
)
|
||||
entry.save()
|
||||
created_lecturers.append(entry) # Objekt der Liste hinzufügen
|
||||
except KeyError as e:
|
||||
# Fehlerbehandlung bei fehlenden Schlüsseln
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop.. Arguments: {3!r}. Message: [{4}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e,
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
except Exception as e:
|
||||
# Allgemeine Fehlerbehandlung
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop. Arguments: {3!r}. Message: {4}."
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e.__str__(),
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
|
||||
return {
|
||||
"Serializer": "Lecturer",
|
||||
"status": "success",
|
||||
"created_count": len(created_lecturers),
|
||||
} # Rückgabe des Erfolgsstatus
|
||||
|
||||
def validate(self, data):
|
||||
# Validierung, um sicherzustellen, dass 'revision' und 'array' Felder vorhanden sind
|
||||
if "revision" not in data.keys():
|
||||
raise serializers.ValidationError("Das 'revision'-Feld ist erforderlich.")
|
||||
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"Das 'array'-Feld ist erforderlich und muss als Python-Liste verfügbar sein."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]} # Rückgabe des validierten Datenarrays
|
||||
|
||||
|
||||
class Attendance_JSON_Serializer(serializers.Serializer):
|
||||
# Definiert die Felder, die der Serializer erwartet
|
||||
revision = serializers.CharField(required=True)
|
||||
array = serializers.ListField()
|
||||
|
||||
|
||||
def create(self, validated_data):
|
||||
# Definieren der erwarteten Schlüssel im JSON-Daten
|
||||
idKey = "dozentenkennung"
|
||||
yearKey = "jahr"
|
||||
monthKey = "monat"
|
||||
dayKey = "tag"
|
||||
hourKey = "stunde"
|
||||
minuteKey = "minute"
|
||||
weekdayKey = "wochentag"
|
||||
dateKey = "termin"
|
||||
|
||||
created_attendences = (
|
||||
[]
|
||||
) # Liste zum Speichern der erstellten Attendance-Objekte
|
||||
try:
|
||||
# Schleife über die Daten, um Attendance-Objekte zu erstellen
|
||||
for iteration_number, d in enumerate(validated_data["dataArray"]):
|
||||
# Überprüfung, ob das 'termin'-Feld vorhanden ist
|
||||
keyAvailable = "termin" in d
|
||||
if not keyAvailable:
|
||||
# Warnung ausgeben, wenn kein Termin zugewiesen wurde
|
||||
template = "Warning. Following Exam was not assigned any examination date ['termin']: [{1}]"
|
||||
message = template.format(d[idKey])
|
||||
JsonParser.warningMessages.append(message)
|
||||
continue
|
||||
|
||||
# Datum und Uhrzeit aus den Daten extrahieren
|
||||
date = datetime.date(
|
||||
d[dateKey][yearKey], d[dateKey][monthKey], d[dateKey][dayKey]
|
||||
)
|
||||
time = datetime.time(d[dateKey][hourKey], d[dateKey][minuteKey])
|
||||
|
||||
# Attendance-Objekt erstellen und speichern
|
||||
entry = Attendance(
|
||||
identification=d[idKey],
|
||||
time=time,
|
||||
date=date,
|
||||
dateTimeText=d[dateKey]["datumText"],
|
||||
weekday=d[dateKey]["wochentag"],
|
||||
)
|
||||
entry.save()
|
||||
created_attendences.append(entry) # Objekt der Liste hinzufügen
|
||||
|
||||
try:
|
||||
# Dozent aus der Datenbank abrufen und mit der Anwesenheit verknüpfen
|
||||
lecturer = Lecturer.objects.get(identification=d[idKey])
|
||||
lecturer.attendance_set.add(
|
||||
entry
|
||||
) # Attendance dem Lecturer zuweisen
|
||||
except Exception as e:
|
||||
# Fehlerbehandlung, wenn der Dozent nicht gefunden wird
|
||||
template = "Exception of type [{0}]. Arguments: {1!r}. Message: [{2}] entry might be missing"
|
||||
message = template.format(type(e).__name__, e.args, idKey)
|
||||
JsonParser.exceptionMessages.append(
|
||||
message
|
||||
) # Fehlermeldung speichern
|
||||
|
||||
except KeyError as e:
|
||||
# Fehlerbehandlung bei fehlenden Schlüsseln
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop.. Arguments: {3!r}. Message: [{4}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e,
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
except Exception as e:
|
||||
# Allgemeine Fehlerbehandlung
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop. Arguments: {3!r}. Message: {4}."
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e.__str__(),
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
|
||||
return {
|
||||
"Serializer": "Attendance",
|
||||
"status": "success",
|
||||
"created_count": len(created_attendences),
|
||||
} # Rückgabe des Erfolgsstatus
|
||||
|
||||
def validate(self, data):
|
||||
# Validierung, um sicherzustellen, dass 'revision' und 'array' Felder vorhanden sind
|
||||
if "revision" not in data.keys():
|
||||
raise serializers.ValidationError("Das 'revision'-Feld ist erforderlich.")
|
||||
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"Das 'array'-Feld ist erforderlich und muss als Python-Liste verfügbar sein."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]} # Rückgabe des validierten Datenarrays
|
||||
|
||||
|
||||
class Subject_JSON_Serializer(serializers.Serializer):
|
||||
# Definiert die Felder, die der Serializer erwartet
|
||||
revision = serializers.CharField(required=True)
|
||||
array = serializers.ListField()
|
||||
|
||||
|
||||
def create(self, validated_data):
|
||||
# Definieren der erwarteten Schlüssel im JSON-Daten
|
||||
idKey = "kennung"
|
||||
initialsKey = "kurztext"
|
||||
nameKey = "langtext"
|
||||
ohmIdKey = "fachkennungOhm"
|
||||
|
||||
created_subjects = [] # Liste zum Speichern der erstellten Subject-Objekte
|
||||
try:
|
||||
# Schleife über die Daten, um Subject-Objekte zu erstellen
|
||||
for iteration_number, d in enumerate(validated_data["dataArray"]):
|
||||
# Subject-Objekt erstellen und speichern
|
||||
entry = Subject(
|
||||
identification=d[idKey],
|
||||
initials=d[ohmIdKey][initialsKey],
|
||||
name=d[ohmIdKey][nameKey],
|
||||
)
|
||||
entry.save()
|
||||
created_subjects.append(entry) # Objekt der Liste hinzufügen
|
||||
|
||||
except KeyError as e:
|
||||
# Fehlerbehandlung bei fehlenden Schlüsseln
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop.. Arguments: {3!r}. Message: [{4}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e,
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
except Exception as e:
|
||||
# Allgemeine Fehlerbehandlung
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop. Arguments: {3!r}. Message: {4}."
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e.__str__(),
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message) # Fehlermeldung speichern
|
||||
|
||||
return {
|
||||
"Serializer": "Subject",
|
||||
"status": "success",
|
||||
"created_count": len(created_subjects),
|
||||
} # Rückgabe des Erfolgsstatus
|
||||
|
||||
def validate(self, data):
|
||||
# Validierung, um sicherzustellen, dass 'revision' und 'array' Felder vorhanden sind
|
||||
if "revision" not in data.keys():
|
||||
raise serializers.ValidationError("Das 'revision'-Feld ist erforderlich.")
|
||||
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"Das 'array'-Feld ist erforderlich und muss als Python-Liste verfügbar sein."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]} # Rückgabe des validierten Datenarrays
|
||||
|
||||
|
||||
class Exam_JSON_Serializer(serializers.Serializer):
|
||||
# Define the fields expected by the serializer
|
||||
revision = serializers.CharField(required=True)
|
||||
array = serializers.ListField()
|
||||
|
||||
def create(self, validated_data):
|
||||
# Define the expected keys in the JSON data
|
||||
idKey = "kennung"
|
||||
yearKey = "jahr"
|
||||
monthKey = "monat"
|
||||
dayKey = "tag"
|
||||
hourKey = "stunde"
|
||||
minuteKey = "minute"
|
||||
weekdayKey = "wochentag"
|
||||
dateKey = "termin"
|
||||
partialExamsKey = "teilpruefungen"
|
||||
partialExamIdKey = "kennung"
|
||||
numRegStudKey = "anzahlAnmeldungen"
|
||||
subjectIdsKey = "fachkennungen"
|
||||
examExecutionsKey = "pruefungsdurchfuehrungen"
|
||||
lecturerIdKey = "dozentenkennung"
|
||||
supervisorTypeKey = "typ"
|
||||
locationKey = "raum"
|
||||
|
||||
created_exams = [] # List to store created Exam objects
|
||||
created_partialexams = [] # List to store created Exam objects
|
||||
ignored_Vorgezogen_exams = 0 # List to ignored Exam objects
|
||||
ignored_KeinTermin_exams = 0 # List to ignored Exam objects
|
||||
try:
|
||||
# Iterate over the data to create Exam objects
|
||||
for iteration_number, d in enumerate(validated_data["dataArray"]):
|
||||
|
||||
# Certain exam entries are ignored
|
||||
if d["pruefungsart"] == "LN_VORGEZOGEN": # These entries can be ignored
|
||||
ignored_Vorgezogen_exams += 1
|
||||
continue
|
||||
|
||||
keyAvailable = "termin" in d
|
||||
if not keyAvailable:
|
||||
# Warning if no examination date is assigned
|
||||
template = "Warning. Following Exam was not assigned any examination date ['termin']: [{0}]"
|
||||
message = template.format(d[idKey])
|
||||
JsonParser.warningMessages.append(message)
|
||||
ignored_KeinTermin_exams += 1
|
||||
continue
|
||||
|
||||
# Extract date and time for the exam
|
||||
date = datetime.date(
|
||||
d[dateKey][yearKey], d[dateKey][monthKey], d[dateKey][dayKey]
|
||||
)
|
||||
time = datetime.time(d[dateKey][hourKey], d[dateKey][minuteKey])
|
||||
|
||||
# Create and save a new Exam entry
|
||||
examEntry = Exam(
|
||||
identification=d[idKey],
|
||||
date=date,
|
||||
time=time,
|
||||
weekday=d[dateKey][weekdayKey],
|
||||
)
|
||||
examEntry.save()
|
||||
created_exams.append(examEntry)
|
||||
|
||||
# Create PartialExam entries and link them with the main exam
|
||||
for teilpruef in d[partialExamsKey]:
|
||||
partialExamId = teilpruef[partialExamIdKey]
|
||||
regStudCount = teilpruef[numRegStudKey]
|
||||
|
||||
# Create and save a new PartialExam entry
|
||||
partialExam = PartialExam(
|
||||
identification=partialExamId, regStudCount=regStudCount
|
||||
)
|
||||
partialExam.save()
|
||||
created_partialexams.append(partialExam)
|
||||
|
||||
# Link Exam and PartialExam (One-to-Many relationship)
|
||||
examEntry.partialexam_set.add(partialExam)
|
||||
|
||||
# Link subjects to the PartialExams
|
||||
for subId in teilpruef[subjectIdsKey]:
|
||||
try:
|
||||
# Check if the subject exists and link it
|
||||
subject = Subject.objects.get(identification=subId)
|
||||
partialExam.subjectIds.add(
|
||||
subject
|
||||
) # Many-to-Many relationship
|
||||
except Exception as e:
|
||||
# Log an error if the subject is not found
|
||||
template = "Exception of type [{0}]. Arguments: {1!r}. Message: [{2}] entry might be missing"
|
||||
message = template.format(type(e).__name__, e.args, subId)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
|
||||
# Link exam executions to PartialExams
|
||||
for pruefdurch in teilpruef[examExecutionsKey]:
|
||||
lecId = pruefdurch[lecturerIdKey]
|
||||
supervisorType = pruefdurch[supervisorTypeKey]
|
||||
location = pruefdurch[locationKey]
|
||||
|
||||
# Create and save a new ExamExecution entry
|
||||
examExecution = ExamExecution(
|
||||
supervisorType=supervisorType, location=location
|
||||
)
|
||||
examExecution.save()
|
||||
|
||||
# Check if the lecturer exists and link the exam execution
|
||||
try:
|
||||
lecturer = Lecturer.objects.get(pk=lecId)
|
||||
lecturer.examexecution_set.add(
|
||||
examExecution
|
||||
) # One-to-Many relationship
|
||||
except Exception as e:
|
||||
# Log an error if the lecturer is not found
|
||||
template = "Exception of type [{0}]. Arguments: {1!r}. Message: [{2}] entry might be missing"
|
||||
message = template.format(type(e).__name__, e.args, lecId)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
|
||||
# Link subjects to the ExamExecution
|
||||
for subId in pruefdurch[subjectIdsKey]:
|
||||
try:
|
||||
# Check if the subject exists and link it
|
||||
subject = Subject.objects.get(identification=subId)
|
||||
examExecution.subjectIds.add(
|
||||
subject
|
||||
) # Many-to-Many relationship
|
||||
except Exception as e:
|
||||
# Log an error if the subject is not found
|
||||
template = "Exception of type [{0}]. Arguments: {1!r}. Message: [{2}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__, e.args, subId
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
|
||||
# Link PartialExam and ExamExecution (One-to-Many relationship)
|
||||
partialExam.examexecution_set.add(examExecution)
|
||||
|
||||
except KeyError as e:
|
||||
# Error handling for missing keys in the dict
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop.. Arguments: {3!r}. Message: [{4}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e,
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
except Exception as e:
|
||||
# General error handling
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop. Arguments: {3!r}. Message: {4}."
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e.__str__(),
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
|
||||
return {
|
||||
"Serializer": "Exam",
|
||||
"status": "success",
|
||||
"created_Exams": len(created_exams),
|
||||
"created_PartialExams_count": len(created_partialexams),
|
||||
"ignored_Exams -> Vorgezogen": ignored_Vorgezogen_exams,
|
||||
"ignored_Exams -> Kein Termin": ignored_KeinTermin_exams,
|
||||
}
|
||||
|
||||
def validate(self, data):
|
||||
# Validation for the 'revision' field
|
||||
if "revision" not in data.keys():
|
||||
raise serializers.ValidationError("The 'revision' field is required.")
|
||||
|
||||
# Validation for the 'array' field
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"The 'array' field is required and must be a Python list."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]}
|
||||
|
||||
|
||||
class RoomAllocation_JSON_Serializer(serializers.Serializer):
|
||||
# Define the fields expected by the serializer
|
||||
revision = serializers.CharField(required=True)
|
||||
array = serializers.ListField()
|
||||
|
||||
def create(self, validated_data):
|
||||
# Define the expected keys in the JSON data
|
||||
idKey = "kennungPruefung"
|
||||
yearKey = "jahr"
|
||||
monthKey = "monat"
|
||||
dayKey = "tag"
|
||||
hourKey = "stunde"
|
||||
minuteKey = "minute"
|
||||
weekdayKey = "wochentag"
|
||||
locationKey = "raum"
|
||||
dateKey = "termin"
|
||||
matrikelKey = "matrikel"
|
||||
|
||||
created_roomAllocations = [] # List to store created StudentExam objects
|
||||
try:
|
||||
# Iterate over the data to create StudentExam objects
|
||||
for iteration_number, d in enumerate(validated_data["dataArray"]):
|
||||
# Extract date and time
|
||||
date = datetime.date(
|
||||
d[dateKey][yearKey], d[dateKey][monthKey], d[dateKey][dayKey]
|
||||
)
|
||||
time = datetime.time(d[dateKey][hourKey], d[dateKey][minuteKey])
|
||||
|
||||
# Find the corresponding Exam entry
|
||||
exam = Exam.objects.filter(
|
||||
identification=d[idKey], date=date, time=time
|
||||
).first()
|
||||
|
||||
# Iterate through partial exams and their executions
|
||||
partialExams = exam.partialexam_set.all()
|
||||
for partialExam in partialExams:
|
||||
examExecutions = partialExam.examexecution_set.all()
|
||||
for examExecution in examExecutions:
|
||||
# Check if the location matches and create StudentExam entry
|
||||
if examExecution.location == d[locationKey]:
|
||||
studentExamEntry = StudentExam(
|
||||
examIdentification=d[idKey],
|
||||
date=date,
|
||||
time=time,
|
||||
weekday=d[dateKey][weekdayKey],
|
||||
location=d[locationKey],
|
||||
examExecution=examExecution,
|
||||
)
|
||||
studentExamEntry.save()
|
||||
created_roomAllocations.append(studentExamEntry)
|
||||
|
||||
# Create or update Student entries
|
||||
for matrikel in d[matrikelKey]:
|
||||
studentEntry = Student.objects.filter(matrikel=matrikel).exists()
|
||||
if not studentEntry:
|
||||
# Create a new Student entry if it doesn't exist
|
||||
entry = Student(matrikel=matrikel)
|
||||
entry.save()
|
||||
else:
|
||||
entry = Student.objects.all().filter(matrikel=matrikel).first()
|
||||
entry.exams.add(studentExamEntry)
|
||||
except KeyError as e:
|
||||
# Error handling for missing keys in the dict
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop.. Arguments: {3!r}. Message: [{4}] entry might be missing"
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e,
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
except Exception as e:
|
||||
# General error handling
|
||||
calling_function = inspect.stack()[0][3]
|
||||
template = "Exception of type [{0}] occurred in function {1} in iteration {2} of the loop. Arguments: {3!r}. Message: {4}."
|
||||
message = template.format(
|
||||
type(e).__name__,
|
||||
calling_function,
|
||||
iteration_number,
|
||||
e.args,
|
||||
e.__str__(),
|
||||
)
|
||||
JsonParser.exceptionMessages.append(message)
|
||||
|
||||
return {
|
||||
"Serializer": "RoomAllocation",
|
||||
"status": "success",
|
||||
"created_RoomAllocations": len(created_roomAllocations),
|
||||
}
|
||||
|
||||
def validate(self, data):
|
||||
# Validation for the 'revision' field
|
||||
if "revision" not in data.keys():
|
||||
raise serializers.ValidationError("The 'revision' field is required.")
|
||||
|
||||
# Validation for the 'array' field
|
||||
if "array" not in data or not isinstance(data["array"], list):
|
||||
raise serializers.ValidationError(
|
||||
"The 'array' field is required and must be a Python list."
|
||||
)
|
||||
|
||||
return {"dataArray": data["array"]}
|
||||
@@ -0,0 +1,24 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
from rest_framework_simplejwt.views import TokenRefreshView
|
||||
from rest_framework.authtoken.views import obtain_auth_token
|
||||
|
||||
urlpatterns = [
|
||||
path(
|
||||
"user/token",
|
||||
views.MyTokenObtainPairView.as_view(),
|
||||
), # URL to classview fpr token interactions "as_view()"
|
||||
path(
|
||||
"user/token/refresh/", TokenRefreshView.as_view()
|
||||
), # Lib view from rest_framework to refresh the given token
|
||||
path("user/logoutUser", views.logoutUser),
|
||||
path("user/checkUser", views.checkLoginStatus),
|
||||
path("fetchExamData", views.getAPI_ExamDataSet_ForStudent),
|
||||
path("pruefplanUpload/", views.PruefPlanUploader.as_view()),
|
||||
path("api-token-auth/", obtain_auth_token),
|
||||
path("addlecturer", views.addLecturer),
|
||||
path("addAttendance", views.addAttendance),
|
||||
path("addSubject", views.addSubject),
|
||||
path("addExam", views.addExam),
|
||||
path("addRoomAllocation", views.addRoomAllocation),
|
||||
]
|
||||
@@ -0,0 +1,250 @@
|
||||
from datetime import date
|
||||
import time
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from pruefplan_viewer.models import *
|
||||
from .serializer import *
|
||||
|
||||
from django.contrib.auth import authenticate, login, logout
|
||||
from django.shortcuts import render
|
||||
from api import serializer as api_serializer
|
||||
from rest_framework_simplejwt.views import TokenObtainPairView
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.utils.encoding import force_str
|
||||
|
||||
|
||||
# Create a REST API view class to interact with the custom token serializer class
|
||||
class MyTokenObtainPairView(TokenObtainPairView):
|
||||
# Setup the serializer -> using custom serializer
|
||||
serializer_class = api_serializer.MyTokenObtainPairSerializer
|
||||
|
||||
# Func to handle a post request on this API endpoint
|
||||
def post(self, request, *args, **kwargs):
|
||||
username = request.data.get("username")
|
||||
password = request.data.get("password")
|
||||
|
||||
# User authentication using LADP agains the TH-Server -> Setup LADP in settings.py
|
||||
user = authenticate(username=username, password=password)
|
||||
if not user:
|
||||
return Response({"error": "Invalid credentials"}, status=400)
|
||||
|
||||
# Login the user for Backend authentication
|
||||
login(request=request, user=user)
|
||||
|
||||
# Delegate the post request to the TokenObptainPairView class
|
||||
# Executing the standart jwt creation workflow -> using the custom serializer
|
||||
return super().post(request, *args, **kwargs)
|
||||
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def logoutUser(request):
|
||||
logout(request)
|
||||
return Response()
|
||||
|
||||
|
||||
# Extract the location key and map it to a URL
|
||||
def map_location(location_str):
|
||||
URL_MAP = {
|
||||
"B": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/b-standort-bahnhofstrasse/",
|
||||
"F": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/f-standort-auf-aeg/",
|
||||
"H": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/h-standort-hohfederstrasse/",
|
||||
"K": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/k-standort-kesslerplatz/",
|
||||
"NM": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/nm-standort-neumarkt-in-der-oberpfalz/",
|
||||
"SC": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/sc-standort-innere-cramer-klett-strasse/",
|
||||
"SG": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/sg-standort-karl-grillenberger-strasse/",
|
||||
"SK": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/sk-standort-prof-ernst-nathan-strasse/",
|
||||
"SP": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/sp-standort-kesslerstrasse/",
|
||||
"SR": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/sr-standort-rednitzhembach/",
|
||||
"W": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/w-standort-wassertorstrasse/",
|
||||
"OL": "Online",
|
||||
"MC": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/pruefungsstandort-mensa-insel-schuett/",
|
||||
"Default": "https://www.th-nuernberg.de/wie-erreichen-sie-uns/anfahrt/",
|
||||
}
|
||||
if not location_str:
|
||||
return URL_MAP["Default"] # Fallback URL if location is empty or None
|
||||
|
||||
location_key = location_str.split(".")[0] # Get the first part before '.'
|
||||
|
||||
# Find the matching key
|
||||
for key in URL_MAP.keys():
|
||||
if location_key.startswith(key):
|
||||
return URL_MAP[key]
|
||||
|
||||
return URL_MAP["Default"] # If no match is found, return the default URL
|
||||
|
||||
|
||||
def get_Subject(exam):
|
||||
partialExam = PartialExam.objects.filter(identification=exam).first()
|
||||
subjects = partialExam.subjectIds
|
||||
result = [subject.name for subject in subjects]
|
||||
pass
|
||||
|
||||
|
||||
class PruefPlanUploader(APIView):
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def post(self, request):
|
||||
timeStart = time.perf_counter()
|
||||
JsonParser().clearTable()
|
||||
dataSets = [dataSet for dataSet in request.data]
|
||||
|
||||
serializers = [
|
||||
Lecturer_JSON_Serializer(data=dataSets[0]),
|
||||
Attendance_JSON_Serializer(data=dataSets[1]),
|
||||
Subject_JSON_Serializer(data=dataSets[2]),
|
||||
Exam_JSON_Serializer(data=dataSets[3]),
|
||||
RoomAllocation_JSON_Serializer(data=dataSets[4]),
|
||||
]
|
||||
|
||||
respondList = [
|
||||
serializer.save() for serializer in serializers if serializer.is_valid()
|
||||
]
|
||||
|
||||
partial_delta = generate_ExamDataSet_ForStudent()
|
||||
timeEnd = time.perf_counter()
|
||||
|
||||
total_delta = timeEnd - timeStart
|
||||
respondList.append({"Uploadtime_in_Sekonds": {round(total_delta, ndigits=2)}})
|
||||
respondList.append({"ExamDataSettime_in_Sekonds": {round(partial_delta, ndigits=2)}})
|
||||
|
||||
return Response(respondList)
|
||||
|
||||
|
||||
@api_view(["GET"])
|
||||
def getAPI_ExamDataSet_ForStudent(request):
|
||||
exam_data = API_ExamDataSet_ForStudent.objects.all()
|
||||
|
||||
# Serialize the data using the ModelSerializer
|
||||
serializer = API_ExamDataSet_ForStudentSerializer(exam_data, many=True)
|
||||
|
||||
return Response(serializer.data) # This will return the data as JSON
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def pruefplanUpload(request):
|
||||
|
||||
timeStart = time.perf_counter()
|
||||
dataSets = [dataSet for dataSet in request.data]
|
||||
|
||||
serializers = [
|
||||
Lecturer_JSON_Serializer(data=dataSets[0]),
|
||||
Attendance_JSON_Serializer(data=dataSets[1]),
|
||||
Subject_JSON_Serializer(data=dataSets[2]),
|
||||
Exam_JSON_Serializer(data=dataSets[3]),
|
||||
RoomAllocation_JSON_Serializer(data=dataSets[4]),
|
||||
]
|
||||
respondList = [
|
||||
serializer.save() for serializer in serializers if serializer.is_valid()
|
||||
]
|
||||
|
||||
generate_ExamDataSet_ForStudent()
|
||||
timeEnd = time.perf_counter()
|
||||
|
||||
delta = timeEnd - timeStart
|
||||
print(f"Time for Upload: {round(delta)}s")
|
||||
respondList.append(delta)
|
||||
|
||||
return Response(respondList)
|
||||
|
||||
|
||||
def generate_ExamDataSet_ForStudent():
|
||||
timeStart = time.perf_counter()
|
||||
students = Student.objects.all()
|
||||
|
||||
for student in students:
|
||||
for studentExam in student.exams.all():
|
||||
|
||||
examDataSet_ForStudent = API_ExamDataSet_ForStudent(
|
||||
date=studentExam.date,
|
||||
time=studentExam.time,
|
||||
weekday=studentExam.weekday,
|
||||
room=studentExam.location,
|
||||
location=map_location(studentExam.location),
|
||||
subjectIdent=list(
|
||||
{
|
||||
subject.name
|
||||
for subject in studentExam.examExecution.partialExam.subjectIds.all()
|
||||
}
|
||||
)[0],
|
||||
examIdent=studentExam.examIdentification,
|
||||
examStudCount=studentExam.examExecution.partialExam.regStudCount,
|
||||
supervisor=f"{studentExam.examExecution.lecturer.firstName} {studentExam.examExecution.lecturer.lastName}",
|
||||
studMartNr=student.matrikel,
|
||||
)
|
||||
examDataSet_ForStudent.save()
|
||||
|
||||
timeEnd = time.perf_counter()
|
||||
delta = timeEnd - timeStart
|
||||
return delta
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def checkLoginStatus(request):
|
||||
username = request.data["username"]
|
||||
if User.objects.filter(username=username).exists():
|
||||
usr = User.objects.get(username=username)
|
||||
if usr.is_authenticated:
|
||||
return Response(data="IsLoggedin")
|
||||
else:
|
||||
return Response(data="IsNotLoggedin")
|
||||
else:
|
||||
return Response(data="No user exist with this {} username.".format(username))
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def addLecturer(request):
|
||||
serializer = Lecturer_JSON_Serializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
Lecturer_JASON_Serializer_Respond = (
|
||||
serializer.save()
|
||||
) # Hier wird der Rückgabewert von create() erfasst
|
||||
# Erstelle eine Response basierend auf den erstellten Lecturer-Objekten
|
||||
return Response(Lecturer_JASON_Serializer_Respond)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def addAttendance(request):
|
||||
serializer = Attendance_JSON_Serializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
Attendance_JSON_Serializer_Respond = (
|
||||
serializer.save()
|
||||
) # Hier wird der Rückgabewert von create() erfasst
|
||||
# Erstelle eine Response basierend auf den erstellten Lecturer-Objekten
|
||||
return Response(Attendance_JSON_Serializer_Respond)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def addSubject(request):
|
||||
serializer = Subject_JSON_Serializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
Subject_JASON_Serializer_Respond = (
|
||||
serializer.save()
|
||||
) # Hier wird der Rückgabewert von create() erfasst
|
||||
# Erstelle eine Response basierend auf den erstellten Lecturer-Objekten
|
||||
return Response(Subject_JASON_Serializer_Respond)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def addExam(request):
|
||||
serializer = Exam_JSON_Serializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
Exam_JASON_Serializer_Respond = (
|
||||
serializer.save()
|
||||
) # Hier wird der Rückgabewert von create() erfasst
|
||||
# Erstelle eine Response basierend auf den erstellten Lecturer-Objekten
|
||||
return Response(Exam_JASON_Serializer_Respond)
|
||||
|
||||
|
||||
@api_view(["POST"])
|
||||
def addRoomAllocation(request):
|
||||
serializer = RoomAllocation_JSON_Serializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
RoomAllocation_JASON_Serializer_Respond = (
|
||||
serializer.save()
|
||||
) # Hier wird der Rückgabewert von create() erfasst
|
||||
# Erstelle eine Response basierend auf den erstellten Lecturer-Objekten
|
||||
return Response(RoomAllocation_JASON_Serializer_Respond)
|
||||
Reference in New Issue
Block a user