gpt4 book ai didi

python - django s3 boto文件上传TypeError : invalid file:
转载 作者:行者123 更新时间:2023-11-28 17:30:00 26 4
gpt4 key购买 nike

我正在尝试将文件从 postman 上传到 s3 并在k.set_contents_from_filename(文件)类型错误:无效文件:你能看看吗?非常感谢。

序列化器.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)

View .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)

实用程序.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

网址.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

最佳答案

您正在将 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)

Store an object in S3 using the name of the Key object as the key in S3 and the contents of the file named by ‘filename’. See set_contents_from_file method for details about the parameters.

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

关于python - django s3 boto文件上传TypeError : invalid file: <InMemoryUploadedFile:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35142529/

26 4 0

Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com