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

后端 未结 5 1650
忘了有多久
忘了有多久 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:28

    Python 3 users: make sure you open the file in mode='rb' (read,binary). Otherwise, when Django calls read on the file the utf-8 codec will immediately start choking. The file should be decoded as binary not utf-8, ascii or any other encoding.

    # This won't work in Python 3
    with open(tmp_file.name) as fp:
            response = self.client.post('my_url', 
                                       {'image': fp}, 
                                       format='multipart')
    
    # Set the mode to binary and read so it can be decoded as binary
    with open(tmp_file.name, 'rb') as fp:
            response = self.client.post('my_url', 
                                       {'image': fp}, 
                                       format='multipart')
    

提交回复
热议问题