views.py 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. from rest_framework import generics, status
  2. from rest_framework.response import Response
  3. from rest_framework.parsers import MultiPartParser
  4. from datetime import datetime
  5. from boto3.session import Session
  6. import os
  7. import environ
  8. from .serializers import FileSerializer
  9. env = environ.Env(DEBUG=(bool, False))
  10. environ.Env.read_env()
  11. class FileUploadView(generics.GenericAPIView):
  12. serializer_class = FileSerializer
  13. parser_classes = (MultiPartParser, )
  14. def post(self, request, format=None):
  15. serializer = self.get_serializer(data=request.FILES)
  16. serializer.is_valid(raise_exception=True)
  17. file_extension = os.path.splitext(str(request.FILES['file']))[1]
  18. filename = datetime.now().strftime("%d-%m-%YT%H:%M:%S") + file_extension
  19. session = Session(region_name=env('REGION_NAME'),
  20. aws_access_key_id=env('AWS_ACCESS_KEY_ID'),
  21. aws_secret_access_key=env('AWS_SECRET_ACCESS_KEY'))
  22. s3 = session.resource('s3')
  23. s3.Bucket(env('BUCKET')).put_object(Key=filename, Body=request.FILES['file'])
  24. return Response({"message": "Upload Successful"}, status=status.HTTP_200_OK)