How can I test binary file uploading with django-rest-framework's test client?

后端 未结 5 1655
忘了有多久
忘了有多久 2020-12-05 17:11

I have a Django application with a view that accepts a file to be uploaded. Using the Django REST framework I\'m subclassing APIView and implementing the post() method like

5条回答
  •  悲&欢浪女
    2020-12-05 17:48

    For those in Windows, the answer is a bit different. I had to do the following:

    resp = None
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp_file:
        image = Image.new('RGB', (100, 100), "#ffffd")
        image.save(tmp_file, format="JPEG")
        tmp_file.close()
    
    # create status update
    with open(tmp_file.name, 'rb') as photo:
        resp = self.client.post('/api/articles/', {'title': 'title',
                                                   'content': 'content',
                                                   'photo': photo,
                                                   }, format='multipart')
    os.remove(tmp_file.name)
    

    The difference, as pointed in this answer (https://stackoverflow.com/a/23212515/72350), the file cannot be used after it was closed in Windows. Under Linux, @Meistro's answer should work.

提交回复
热议问题