detail_route methods GET POST def feed self request pk if request meth

 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
@detail_route(methods=['GET', 'POST'])
def feed(self, request, pk):
if request.method == 'GET':
return self.get_feed(request, pk)
elif request.method == 'POST':
return self.post_feed(request, pk)
def get_feed(self, request, pk):
obj = self.get_object()
containing_object_ct = ContentType.objects.get_for_model(obj)
message_ids = Message.objects.filter(content_type=containing_object_ct, object_id=obj.pk)\
.values_list('id', flat=True)
message_ct = ContentType.objects.get_for_model(Message)
notices = Notice.objects.filter(Q(content_type=message_ct, object_id__in=message_ids) |
Q(content_type=containing_object_ct, object_id=obj.id)).order_by('-created')
from_, to = request.query_params.get('from'), request.query_params.get('to')
if from_ is None or len(from_.strip()) == 0:
from_ = '0000-01-01T00:00:00Z'
if to is None or len(to.strip()) == 0:
to = '9999-12-31T23:59:59Z'
try:
from_, to = parser.parse(from_), parser.parse(to)
except ValueError:
pass
else:
notices = notices.filter(created__range=(from_, to))
paginator = Paginator(notices, 5)
try:
page = self.request.query_params.get('page', 1)
page_number = paginator.validate_number(page)
except InvalidPage:
if page == 'last':
page_number = paginator.num_pages
else:
raise Http404("Page is not 'last', nor can it be converted to an int.")
try:
page = paginator.page(page_number)
except InvalidPage as e:
raise Http404('Invalid page (%(page_number)s): %(message)s' % {
'page_number': page_number,
'message': str(e)
})
return Response(NoticeSerializer(page.object_list, many=True).data, status=status.HTTP_200_OK, headers={
'Count': page.paginator.count
})
def post_feed(self, request, pk):
obj = self.get_object()
serializer = MessageSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
text = serializer.validated_data['text']
temp_files_uuids = serializer.validated_data.get('uploaded_files')
message, notice = post_message(obj, request.user, text, temp_files_uuids)
# return notice, instead of message, because of the way feed is implemented
return Response(NoticeSerializer(notice).data, status=status.HTTP_201_CREATED)