-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
522 lines (443 loc) · 17.7 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import swapper
import logging
from django.db import transaction, IntegrityError
from django.db.models import Q
from django.core.exceptions import (
ObjectDoesNotExist,
ValidationError,
ImproperlyConfigured,
FieldDoesNotExist,
)
from django.utils.datastructures import MultiValueDictKeyError
from itertools import chain
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import status, generics
from rest_framework.decorators import action
from rest_framework.parsers import MultiPartParser
from formula_one.models.generics.social_information import SocialLink
from formula_one.serializers.generics.social_information import SocialLinkSerializer
from kernel.managers.get_role import get_role
from kernel.permissions.has_role import get_has_role
from omniport.settings.configuration.base import CONFIGURATION
from student_profile.permissions.is_student import IsStudent
from student_profile.serializers.generic_serializers import common_dict
from student_profile.serializers.student_serializer import StudentSearchSerializer
from student_profile.serializers.profile import ProfileSerializer
from student_profile.tasks.publish_page import publish_page
logger = logging.getLogger('student_profile')
Student = swapper.load_model('kernel', 'Student')
# Add Profile to common_dict
common_dict['Profile'] = {'serializer': ProfileSerializer, 'viewset': None}
models = {}
for key in common_dict:
models[key] = swapper.load_model('student_biodata', key)
def return_viewset(class_name):
"""
A generic function used to generate viewsets for every model.
"""
class Viewset(ModelViewSet):
"""
API endpoint that allows models to be viewed or edited.
"""
serializer_class = common_dict[class_name]["serializer"]
permission_classes = (get_has_role('Student'), )
pagination_class = None
filter_backends = tuple()
def get_queryset(self):
Model = models[class_name]
try:
student = get_role(self.request.person, 'Student')
except:
return []
options = ['priority', 'semester', 'year', 'start_date', 'id']
for option in options[:]:
try:
Model._meta.get_field(option)
except FieldDoesNotExist:
options.remove(option)
return Model.objects.order_by(*options).filter(student=student)
def exception_handler(func):
"""
Decorator to add exception handling to create and update methods.
:param func: function to apply this decorator over
:return: a function which raises an error if the passed function
raises an error
"""
def raise_error(*args, **kwargs):
"""
Wrapper function to raise error
"""
try:
return func(*args, **kwargs)
except IntegrityError as error:
return Response(
{'Fatal error': [error.__cause__.diag.message_detail]},
status=status.HTTP_400_BAD_REQUEST,
)
except ValidationError as error:
return Response(
error.message_dict,
status=status.HTTP_400_BAD_REQUEST,
)
return raise_error
@exception_handler
def create(self, request, *args, **kwargs):
"""
Modify create method to catch errors
"""
return super().create(request, *args, **kwargs)
def perform_create(self, serializer):
"""
modifying perform_create for all the views to get Student
instance from request
"""
student = get_role(self.request.person, 'Student')
serializer.save(student=student)
@exception_handler
def update(self, request, *args, **kwargs):
"""
Modify update method to catch errors
"""
return super().update(request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
class_name = instance.__class__.__name__
if class_name == "PreviousEducation" or class_name == "CurrentEducation":
if instance.verified is True:
return Response("Cannot delete verified education instances", status.HTTP_403_FORBIDDEN)
self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
@action(detail=True, methods=['get'], permission_classes=[])
def handle(self, request, pk=None):
"""
providing an open endpoint for showing the data for normal users
"""
Model = models[class_name]
Profile = models['Profile']
profile = None
try:
student = Student.objects.get(enrolment_number=pk)
profile = Profile.objects.get(student=student)
except ObjectDoesNotExist:
return Response(status=404,)
student = profile.student
options = ['priority', 'semester', 'start_date', 'id']
for option in options[:]:
try:
Model._meta.get_field(option)
except FieldDoesNotExist:
options.remove(option)
objects = Model.objects.order_by(
*options).filter(student=student, visibility=True)
return Response(self.get_serializer(objects, many=True).data)
return Viewset
class SocialLinkViewSet(ModelViewSet):
"""
API endpoint that allows SocialLink Model to be viewed or edited.
"""
permission_classes = (get_has_role('Student'), )
serializer_class = SocialLinkSerializer
pagination_class = None
def get_queryset(self):
person = self.request.person
if person is not None:
socialinformation = person.social_information.filter()
else:
return []
if len(socialinformation) != 0:
queryset = SocialLink.objects.filter(
socialinformation=socialinformation[0]
)
else:
queryset = []
return queryset
def perform_create(self, serializer):
"""
modifying perform_create for all the views to get Student
instance from request
"""
person = self.request.person
link_instance = serializer.save()
si, created = person.social_information.get_or_create()
person.social_information.all()[0].links.add(link_instance)
@action(detail=True, methods=['get'], permission_classes=[])
def handle(self, request, pk=None):
"""
providing an open endpoint fot showing the data for normal users
"""
Model = SocialLink
Profile = models['Profile']
profile = None
try:
student = Student.objects.get(enrolment_number=pk)
profile = Profile.objects.get(student=student)
except ObjectDoesNotExist:
return Response(status=404,)
student = profile.student
options = ['priority', 'semester', 'start_date', 'id']
for option in options[:]:
try:
Model._meta.get_field(option)
except FieldDoesNotExist:
options.remove(option)
social_info = student.person.social_information.first()
links = social_info.links if social_info else list()
return Response(SocialLinkSerializer(links, many=True).data)
for key in common_dict:
common_dict[key]["viewset"] = return_viewset(key)
class ProfileViewset(ModelViewSet):
"""
API endpoint that allows models to be viewed or edited.
"""
serializer_class = common_dict['Profile']['serializer']
permission_classes = (get_has_role('Student'), )
pagination_class = None
filter_backends = tuple()
def get_queryset(self):
Model = models['Profile']
try:
student = get_role(self.request.person, 'Student')
except:
return []
profile = Model.objects.order_by('-id').filter(student=student)
if len(profile) == 0:
profile = Model.objects.create(
student=student, handle=student.enrolment_number, description="Student at IITR")
profile.save()
return [profile]
return profile
def create(self, request, *args, **kwargs):
"""
Modifying create method to add functionality of adding profile image
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
data = serializer.data
person = request.person
try:
img_file = request.data['image']
if img_file is None or img_file == "null":
person.display_picture = None
person.save()
else:
person.display_picture.save(img_file.name, img_file, save=True)
except MultiValueDictKeyError:
logger.info('MultiValueDictKeyError has occurred \
when user tried to upload profile image')
try:
data['displayPicture'] = request.person.display_picture.url
except ValueError:
data['displayPicture'] = None
headers = self.get_success_headers(serializer.data)
return Response(data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
"""
modifying perform_create for all the views to get Student
instance from request
"""
student = get_role(self.request.person, 'Student')
serializer.save(student=student)
def update(self, request, *args, **kwargs):
"""
modifying update function to change image field to null in case of deleting the profile image
"""
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(
instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
parser_class = (MultiPartParser, )
self.perform_update(serializer)
if getattr(instance, '_prefetched_objects_cache', None):
# If 'prefetch_related' has been applied to a queryset, we need to
# forcibly invalidate the prefetch cache on the instance.
instance._prefetched_objects_cache = {}
data = serializer.data
try:
img_file = request.data['image']
person = request.person
if img_file is None or img_file == "null":
person.display_picture = None
person.save()
else:
person.display_picture.save(img_file.name, img_file, save=True)
except MultiValueDictKeyError:
logger.info('MultiValueDictKeyError has occurred \
when user tried to upload profile image')
try:
data['displayPicture'] = request.person.display_picture.url
except ValueError:
data['displayPicture'] = None
return Response(data)
def destroy(self, request, *args, **kwargs):
"""
modifying destroy method to remove only the resume field
"""
instance = self.get_object()
instance.resume = None
instance.save()
serializer = self.get_serializer(instance)
return Response(serializer.data)
@action(detail=True, methods=['get'], permission_classes=[])
def handle(self, request, pk=None):
"""
A view to get the profile information without the authentication
"""
try:
student = Student.objects.get(enrolment_number=pk)
profile = models['Profile'].objects.get(student=student)
data = self.get_serializer(profile).data
try:
data['displayPicture'] = profile.student.person.display_picture.url
except ValueError:
data['displayPicture'] = None
data['fullName'] = profile.student.person.full_name
except ObjectDoesNotExist:
return Response(status=404,)
return Response(data)
common_dict['Profile']["viewset"] = ProfileViewset
class StudentSearchList(generics.ListAPIView):
"""
View to return the student search list.
"""
serializer_class = StudentSearchSerializer
pagination_class = None
def get_queryset(self):
query = self.request.query_params.get('query', None)
students = Student.objects.filter(
Q(enrolment_number__icontains=query) |
Q(profile__handle__icontains=query) |
Q(person__full_name__icontains=query)
).order_by('enrolment_number')[:10]
result = list(chain(students))
return result
class PublishPageView(APIView):
"""
API endpoint to publish a preview page
"""
permission_classes = (get_has_role('Student'), )
SHP = CONFIGURATION.integrations.get('shp', False)
def check_configuration(self):
if self.SHP:
attributes = [
self.SHP.get('shp_publish_endpoint'),
self.SHP.get('shp_publish_token'),
self.SHP.get('shp_url')
]
if all(attributes):
return True
else:
raise ImproperlyConfigured
else:
return False
def get(self, request):
"""
Returns whether SHP configuration exists or not
:return: whether SHP configuration exists or not
"""
try:
is_configured = self.check_configuration()
if is_configured:
return Response(
'SHP configuration detected',
status=status.HTTP_200_OK,
)
return Response(
'You probably do not need students page published',
status=status.HTTP_404_NOT_FOUND,
)
except ImproperlyConfigured:
return Response(
(
'SHP falsely configured. Please provide `shp_publish_endpoint` '
'in the configuration'
),
status=status.HTTP_406_NOT_ACCEPTABLE,
)
def post(self, request):
try:
is_configured = self.check_configuration()
except ImproperlyConfigured:
return Response(
(
'SHP falsely configured. Please provide `shp_publish_endpoint` '
'in the configuration'
),
status=status.HTTP_406_NOT_ACCEPTABLE,
)
if is_configured:
enrolment_number = request.person.student.enrolment_number
student_full_name = request.person.full_name
student_description = request.data.get('description', '')
student_display_picture = request.data.get('display_picture', '')
shp_endpoint = self.SHP.get('shp_publish_endpoint')
shp_token = self.SHP.get('shp_publish_token')
shp_url = self.SHP.get('shp_url')
person = request.person.id
publish_page.delay(
person,
enrolment_number,
student_full_name,
student_display_picture,
student_description,
shp_endpoint,
shp_token,
shp_url
)
return Response(
'Successfully added to publish queue',
status=status.HTTP_200_OK,
)
else:
return Response(
'You probably do not need students page published',
status=status.HTTP_405_METHOD_NOT_ALLOWED,
)
class DragAndDropView(APIView):
"""
API endpoint that allows the changing if the ordering of the models
"""
permission_classes = (get_has_role('Student'), )
pagination_class = None
filter_backends = ()
@transaction.atomic
def post(self, request):
data = request.data
student = get_role(self.request.person, 'Student')
model_name = data['model']
Model = models[model_name]
objects = Model.objects.order_by('id').filter(student=student)
serializer = common_dict[model_name]['serializer']
priority_array = data['order']
if(len(priority_array) == len(objects)):
order = dict()
for i in range(len(priority_array)):
order[priority_array[i]] = i + 1
for obj in objects:
obj.priority = order[obj.id]
obj.save()
return Response(serializer(objects.order_by('priority'), many=True).data)
class VisibilityView(APIView):
"""
API endpoint that allows the changing of visibility of the models
"""
permission_classes = (get_has_role('Student'), )
pagination_class = None
filter_backends = ()
@transaction.atomic
def post(self, request):
data = request.data
student = get_role(self.request.person, 'Student')
model_name = data['model']
visibility = data['visibility']
Model = models[model_name]
objects = Model.objects.order_by('priority').filter(student=student)
serializer = common_dict[model_name]['serializer']
for obj in objects:
obj.visibility = visibility
obj.save()
response = serializer(objects, many = True)
return Response(response.data , status = status.HTTP_200_OK)