- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将文件从 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"),
]
最佳答案
您正在将 Django InMemoryUploadedFile
传递给方法 set_content_from_filename
,它需要一个字符串。
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/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!