11from django .db import transaction
2+ from rest_framework import generics
23from rest_framework import permissions , status
4+ from rest_framework .generics import get_object_or_404
35from rest_framework .response import Response
4- from rest_framework .views import APIView
56
67from files .helpers import FileAPI
78from files .models import UserFile
9+ from files .serializers import UserFileSerializer
810
911
10- class FileView (APIView ):
11- permission_classes = [permissions .AllowAny ]
12+ class FileView (generics .RetrieveDestroyAPIView ):
13+ permission_classes = [permissions .IsAuthenticatedOrReadOnly ]
14+ serializer_class = UserFileSerializer
15+ queryset = UserFile .objects .all ()
1216
1317 @transaction .atomic
1418 def post (self , request ):
19+ """creates a UserFile object and uploads the file to selectel"""
1520 file_api = FileAPI (request .FILES ["file" ], request .user )
1621 status_code , url = file_api .upload ()
1722
@@ -20,3 +25,23 @@ def post(self, request):
2025 return Response ({"url" : url }, status = status .HTTP_201_CREATED )
2126
2227 return Response ("Failed to upload file" , status = status .HTTP_409_CONFLICT )
28+
29+ def delete (self , request , * args , ** kwargs ):
30+ """deletes the file (only if the request is sent by the user who owns it!)
31+ The link has to be specified in the JSON body, not in the URL arguments.
32+ """
33+ if request .data and (request .data .get ("link" ) is not None ):
34+ link = request .data .get ("link" )
35+ else :
36+ return Response (
37+ {
38+ "error" : "you have to pass the link of the object you want to delete as JSON"
39+ },
40+ status = status .HTTP_400_BAD_REQUEST ,
41+ )
42+ instance = get_object_or_404 (self .get_queryset (), link = link )
43+ if instance .user != request .user :
44+ return Response (status = status .HTTP_403_FORBIDDEN )
45+ FileAPI .delete (instance .link ) # delete the file via api
46+ self .perform_destroy (instance )
47+ return Response (status = status .HTTP_204_NO_CONTENT )
0 commit comments