Django s3 boto file download TypeError: invalid file: <InMemoryUploadedFile:

I am trying to upload a file from postman to s3 and get an error at k.set_contents_from_filename (file) TypeError: invalid file: Could you take a look? Many thanks.

serializers.py

from rest_framework import serializers
class ResourceSerializer(serializers.Serializer):
    file = serializers.FileField(required=True, max_length=None, use_url=True)
    name = serializers.CharField(required=True, max_length=500)

views.py

import logging
from boto.s3.key import Key

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from .serializers import ResourceSerializer
from .utils import create_boto_connection
from django.conf import settings


class Resource(APIView):
    def post(self, request, format=None):
        serializer = ResourceSerializer(data=request.data)
        if serializer.is_valid():
            context = {}
            file = serializer.validated_data['file']
            name = serializer.validated_data['name']
            ext = file.name.split('.')[-1]
            new_file_name = '{file}.{ext}'.format(file=name, ext=ext)
            file_name_with_dir = 'profile_photos/{}'.format(new_file_name)
            # Create s3boto connection
            conn = create_boto_connection()
            try:
                bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME)
                k = Key(bucket)
                k.key = file_name_with_dir
                k.set_contents_from_filename(file)
                k.make_public()
                context['file'] = new_file_name
            except Exception as e:
                context['message'] = 'Failed to process request'
                # Logging Exceptions
                logging.exception(e)
                logging.debug("Could not upload to S3")
            return Response(context, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

utils.py

from boto.s3.connection import S3Connection

from django.conf import settings


def create_boto_connection():
    conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    # conn = boto.connect_s3()
    return conn

urls.py

from django.conf.urls import url

from s3boto import views

urlpatterns = [
    # v1
    url(r'^v1/s3boto/upload-resource/$', views.Resource.as_view(), name="upload-resource"),
]

postman: enter image description here

+4
source share
1 answer

You pass django to a InMemoryUploadedFilemethod set_content_from_filenamethat expects a string.

From boto documentation :

set_contents_from_filename (file name, headers = None, replace = True, cb = None, num_cb = 10, policy = None, md5 = None, reduced_redundancy = False, encrypt_key = False)

S3, Key S3 'filename. set_contents_from_file .

set_content_from_file set_content_from_filename.

+3

Source: https://habr.com/ru/post/1626937/


All Articles