热门标签:
Q:

Django REST Framework+Django REST Swagger+ImageField

我用ImageField创建了一个简单的模型,我想用django-rest-framework+django-rest-swagger制作一个api视图,它被记录并能够上传文件。

这是我得到的:

models.py

from django.utils import timezone
from django.db import models

class MyModel(models.Model):

    source = models.ImageField(upload_to=u'/photos')
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"photo {0}".format(self.source.url)

serializer.py

from .models import MyModel

class MyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = [
            'id',
            'source',
            'created_at',
        ]

views.py

from rest_framework import generics
from .serializer import MyModelSerializer

class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FileUploadParser, )

    def post(self, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: source
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return super(MyModelView, self).post(self, *args, **kwargs)

urls.py

from weddings.api.views import MyModelView

urlpatterns = patterns(
    '',
    url(r'^/api/mymodel/$', MyModelView.as_view()),
)

对我来说,这应该很简单。 但是,我无法使上传工作。 我总是得到这个错误响应: 在这里输入图像描述django-rest-framework阅读了这部分文档:

If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

但是,Django-rest-swagger正在请求有效负载属性(来自chrome控制台)中传递标头。

如果需要更多信息,请告诉我。

我正在使用Django==1.8.8djangorestframework==3.3.2django-rest-swagger==0.3.4

原网址
A:

我通过对代码进行一些更改来实现这一点。

首先,在models.py中,将ImageField名称更改为file并使用相对路径上传文件夹。 当您将文件作为二进制流上传时,它在文件键(request.data.get('file'))下的request.data.get('file')字典中可用,所以最干净的选择是将其映射到同名的模型字段。

from django.utils import timezone
from django.db import models


class MyModel(models.Model):

    file = models.ImageField(upload_to=u'photos')
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"photo {0}".format(self.file.url)

serializer.py中,将源字段重命名为文件:

class MyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('id', 'file', 'created_at')

在views.py,不要调用super,而是调用create():

from rest_framework import generics
from rest_framework.parsers import FileUploadParser

from .serializer import MyModelSerializer


class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FileUploadParser,)

    def post(self, request, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: file
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return self.create(request, *args, **kwargs)

我已经使用Postman Chrome扩展来测试这个。 我已经将图像上传为二进制文件,并且我手动设置了两个标题:

Content-Disposition: attachment; filename=upload.jpg
Content-Type: */*

所有回答

共 2 条

author avatar

这是我想出的最终解决方案:

from rest_framework import generics
from rest_framework.parsers import FormParser, MultiPartParser
from .serializer import MyModelSerializer

class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FormParser, MultiPartParser)

    def post(self, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: source
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return super(MyModelView, self).post(self, *args, **kwargs)

我所要做的就是将解析器从FileUploadParser更改为(FormParser, MultiPartParser)

author avatar

根据我的经验,FileUploadParser可以使用这种请求格式:

    curl -X POST -H "Content-Type:multipart/form-data" \
                 -F "file=@{filename};type=image/jpg" \
                 https://endpoint.com/upload-uri/

视图中的request.data['file']将具有该文件。

也许如果你尝试一个Content-Type:multipart/form-data标题,你会有运气。

相似问题