diff --git a/backend/core/api/serializers.py b/backend/core/api/serializers.py index f1a7b64..0a7e0aa 100644 --- a/backend/core/api/serializers.py +++ b/backend/core/api/serializers.py @@ -96,14 +96,16 @@ class Meta: fields = ('service', 'attributes', 'include_history') def create(self, validated_data): - include_history = validated_data.pop('include_history', False) + self.include_history = validated_data.pop('include_history', False) with transaction.atomic(): subscription = super().create(dict(user=self.context['request'].user, **validated_data)) subscription.create_in_service() - if include_history: - subscription.submit_history() return subscription + def submit_history(self): + if self.include_history and self.instance: + self.instance.submit_history() + class SubscriptionSerializer(serializers.HyperlinkedModelSerializer): service = ServiceSerializer() diff --git a/backend/core/api/views.py b/backend/core/api/views.py index bf1e950..2a2780a 100644 --- a/backend/core/api/views.py +++ b/backend/core/api/views.py @@ -65,6 +65,17 @@ class SensorAttributeViewSet(viewsets.ModelViewSet): serializer_class = serializers.SensorAttributeSerializer +class AftereffectResponse(Response): + def __init__(self, *args, **kwargs): + self.aftereffect = kwargs.pop('aftereffect', None) + return super().__init__(*args, **kwargs) + + def close(self): + super().close() + if self.aftereffect: + self.aftereffect() + + class SubscriptionViewSet( viewsets.mixins.ListModelMixin, viewsets.mixins.CreateModelMixin, @@ -100,11 +111,19 @@ def destroy(self, request, *args, **kwargs): return Response(status=status.HTTP_204_NO_CONTENT) def create(self, request, *args, **kwargs): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + try: - return super().create(request, *args, **kwargs) + self.perform_create(serializer) except HTTPError: return Response('Could not register subscription with service.', status=502) + headers = self.get_success_headers(serializer.data) + return AftereffectResponse( + serializer.data, status=status.HTTP_201_CREATED, headers=headers, + aftereffect=lambda: serializer.submit_history()) + @api_view(['POST']) @permission_classes([permissions.AllowAny])