django s3 boto文件上传TypeError:无效文件:<inmemoryuploadedfile:

时间:2016-02-01 23:41:24

标签: python django

=“”

我正在尝试将文件从邮递员上传到s3并收到错误 k.set_contents_from_filename(文件) TypeError:无效文件: 你能看一下吗?非常感谢。

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"),
]
邮递员:enter image description here

1 个答案:

答案 0 :(得分:2)

您正在将django InMemoryUploadedFile传递给方法set_content_from_filename,该方法需要一个字符串。

来自boto documentation

  

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

     

使用Key对象的名称作为键存储S3中的对象   S3和'filename'命名的文件内容。看到   set_contents_from_file方法有关参数的详细信息。

使用set_content_from_file或将文件保存到本地临时文件,并将该文件名传递给set_content_from_filename