2

I'm trying to send two files in a json object with flask restfull and send_file.

When I try to access the json object on client side i get this error:

TypeError: Object of type 'Response' is not JSON serializable

This is what i do i my flask app:

class Download(Resource):
    def get(self):
        try:
            return {"file1" : send_file('uploads/kode.png'), "file2" : send_file('uploads/kode.png')}, 200
        except:
            return {"message" : "File not found!"}, 404

How can I return a json of files?

Gammer
  • 5,453
  • 20
  • 78
  • 121
Kresten
  • 810
  • 13
  • 36
  • What is "a json of files"? What exactly do you expect the user to receive as a response with the code in your question? – ChrisGPT was on strike Nov 23 '19 at 22:33
  • If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script. – Kresten Nov 23 '19 at 22:43

2 Answers2

4

If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script.

You mean like:

return send_file('path/to/file.png')

That works, because Flask's send_file function actually returns a Response object.

This is also valid code (as of flask version 1.1.0):

return {"message" : "File not found!"}, 404

Here you're returning a dictionary with the key 'message' and value 'File not found!'. Flask will turn this into a Response object, with a status code of 404.

That dictionary is jsonified automatically (as of flask version 1.1.0).

When you try to return this:

return {"file1" : send_file('uploads/kode.png')}, 200

The Response object returned by send_file is then jsonified, hence the exception:

TypeError: Object of type 'Response' is not JSON serializable


The obvious way to make this work is that the frontend should make a separate request to the server for each image, passing some kind of ID which the Flask route function should then obtain and use to work out the filepath, then ultimately: return sendfile(filepath).

If you really want to send several images in one JSON response, you could look at base64 encoding the image and making a data_uri string which can be JSON serialized. However unless you really need that data to be passed as JSON, the former option is probably the go-to.

v25
  • 7,096
  • 2
  • 20
  • 36
  • Thanks for the explaination. Why would I not use base64 encoding? Api calls from the frontend are costly. – Kresten Nov 24 '19 at 12:28
1

I think your except is too broad. but to get a json object back, import json and its object.json()

import json
try:
    return file.json()
except Exception as e:
    print(e) 

or your can import the json library from flask

from flask import jsonify
def myMethod():
    ....
    response = jsonify(data)
    response.status_code = 200 # or 400 or whatever
    return response
NotSoary
  • 11
  • 2