Skip to content

Commit f076a42

Browse files
committed
made a path to DELETE /files/
1 parent 565f63c commit f076a42

2 files changed

Lines changed: 37 additions & 3 deletions

File tree

files/serializers.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from rest_framework.serializers import ModelSerializer
2+
3+
from files.models import UserFile
4+
5+
6+
class UserFileSerializer(ModelSerializer):
7+
class Meta:
8+
model = UserFile
9+
fields = ["user", "link", "datetime_uploaded"]

files/views.py

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,22 @@
11
from django.db import transaction
2+
from rest_framework import generics
23
from rest_framework import permissions, status
4+
from rest_framework.generics import get_object_or_404
35
from rest_framework.response import Response
4-
from rest_framework.views import APIView
56

67
from files.helpers import FileAPI
78
from 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

Comments
 (0)