简体   繁体   English

在DRF中支持JSON和文件分段上传的测试

[英]A Test to Support Both JSON and File Multipart Uploads in DRF

I would like to write a test for my DRF app that posts both json and a file using multipart . 我想为我的DRF应用程序编写测试,该应用程序使用multipart发布json和文件。

This is what I have tried so far but collection_items (in the create method) is blank . 这是我到目前为止所尝试的但是collection_items (在create方法中) 是空白的 Do I need to modify my view to make this work correctly, or am I doing something incorrectly within my test case below? 我是否需要修改我的视图以使其正常工作,或者我在下面的测试用例中做错了什么?

My Test: 我的测试:

    image = Image.new('RGB', (100, 100))
    tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
    image.save(tmp_file)

    files = {"collection_items": [{"image": tmp_file}]}
    payload = json.dumps({
        "title": "Test Collection",
    })

    self.api_factory.credentials(Authorization='Bearer ' + self.token)
    response = self.api_factory.post(url, data=payload, files=files, format='multipart')

This is the model: 这是模型:

class Collection(models.Model):

    title = models.CharField(max_length=60)
    collection_items = models.ManyToManyField('collection.Item')


class Item(models.Model):
    image = models.ImageField(upload_to="/",null=True, blank=True)

Serializers: 串行器:

class ItemCollectionDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'image')
        read_only_fields = ('image',)


class CollectionListSerializer(serializers.ModelSerializer):

    url = serializers.HyperlinkedIdentityField(view_name='col_detail')
    collection_items = ItemCollectionDetailSerializer(many=True, required=True)

    class Meta:
        model = Collection
        fields = ('url', 'id', 'collection_items')

    def create(self, validated_data):

        item_data = validated_data.pop('collection_items')

        print(item_data)  # <----- **EMPTY HERE???**

        etc ....edited for brevity

So print(item_data) is empty [], why? 所以print(item_data)是空的[],为什么? How to I resolve this? 我该如何解决这个问题?

This is my entire view: below, do I need to do something here? 这是我的全部观点:下面,我需要在这里做些什么吗?

class CollectionListView(generics.ListCreateAPIView):

    queryset = Collection.objects.all()
    serializer_class = CollectionListSerializer

I am using Django Rest Framework 3.x, Django 1.8.x and Python 3.4.x. 我正在使用Django Rest Framework 3.x,Django 1.8.x和Python 3.4.x.

Update 更新

I have tried below but still no joy! 我试过下面但仍然没有快乐! collection_items is empty in my create . 我的create collection_items为空。 This either has to do with the fact it's a nested object or something has to happen in my view. 这或者与它是一个嵌套对象或者在我的视图中必须发生的事实有关。

    stream = BytesIO()
    image = Image.new('RGB', (100, 100))
    image.save(stream, format='jpeg')
    uploaded_file = SimpleUploadedFile("temp.jpeg", stream.getvalue())

    payload = {
        "title": "Test Collection",
        "collection_items": [{"image": uploaded_file}],
    }

    self.api_factory.credentials(Authorization='Bearer ' + self.test_access.token)
    response = self.api_factory.post(url, data=payload, format='multipart')

Update 2 更新2

If I change my payload to use json.dumps it seems to now see the file but of course this cannot work! 如果我改变我的有效负载使用json.dumps它似乎现在看到文件,但当然这不起作用!

payload = json.dumps({
            "title": "Test Collection",
            "collection_items": [{"image": uploaded_file}],
        })

Error 错误

<SimpleUploadedFile: temp.jpeg (text/plain)> is not JSON serializable

PS PS

I know the file is being uploaded because if I do the following in my serializer... 我知道文件正在上传,因为如果我在序列化程序中执行以下操作...

print(self.context.get("request").data['collection_items'])

I get 我明白了

{'image': <SimpleUploadedFile: temp.jpeg (text/plain)>}

Using the multipart parser you can just pass the file handler in the post arguments (see this ). 使用多部分解析器,您只需在post参数中传递文件处理程序(请参阅此内容 )。 In your code you are submitting a json-encoded part as the data payload and the file part in a files argument, and I don't think it can work that way. 在你的代码中,你提交了一个json编码的部分作为数据有效负载和files参数的文件部分,我不认为它可以这样工作。

Try this code: 试试这段代码:

from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import SimpleUploadedFile

stream = BytesIO()
image = Image.new('RGB', (100, 100))
image.save(stream, format='jpeg')

uploaded_file = SimpleUploadedFile("file.jpg", stream.getvalue(), content_type="image/jpg")
payload = {
    "title": "Test collection",
    "collection_items": [{"image": uf}],
}
self.api_factory.credentials(Authorization='Bearer ' + self.token)
self.api_factory.post(url, data=payload, format='multipart')
...

I'm not entirely sure the nested serialization works, but at least the file upload should work. 我不完全确定嵌套序列化是否有效,但至少文件上传应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM