Sending a file with json with requests and tastypie

81 Views Asked by At

I'm trying to send some zip files, and some json to my tastypie endpoint.

I'm getting:

The format indicated \'multipart/form-data\' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer."

On my client.

This is my client code:

def sendLogs():
url = "api/ziprel/"
payload = {"param_1": "value_1","param_2": "value_2"}
files = {
    'JSON': (None, json.dumps(payload), 'application/json'),
    'Console': (os.path.basename('/home/pi/Desktop/Console.zip'), open('/home/pi/Desktop/Console.zip','rb'), 'application/zip')
}
r = requests.post(url,files=files)
print(r.content)

I get the error when I print, r.content.

Here's my tastypie code:

class MultipartResource(object):
def deserialize(self, request, data, format=None):
    try:
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded')
        if format == 'application/x-www-form-urlencoded':
            return request.POST
        if 'multipart' in format:
            data = request.POST.copy()
            data.update(request.FILES)
            # Get the error here
            json.loads(request.body)
            zip = TestZipModel()
            zip.ADB = request.FILES['ADB']
            zip.save()
            return data
    except Exception as e:
        print("Error {}".format(e))
    return super(MultipartResource, self).deserialize(request, data, format)

# overriding the save method to prevent the object getting saved twice
def obj_create(self, bundle, request=None, **kwargs):
    pass

The server is getting:

Error 'utf-8' codec can't decode byte 0x95 in position 350: invalid start byte

Am I able to send JSON with a multipart/form-data content type? Is there a better way to do this? Sending data along with the zips will be very helpful.

1

There are 1 best solutions below

0
nesto.prikladno On

You could do it like this:

files = {'file': ('download_name.zip', open('file_name.zip', 'rb'), 'application/zip')}
payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post(url, data=payload, files=files) # could do params=payload instead data=payload (URL params)

Example handling in flask:

data = request.form
file = request.files['file']