Kresten
Kresten

Reputation: 838

How can I return a json of files with python flask-restfull?

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?

Upvotes: 2

Views: 7183

Answers (2)

v25
v25

Reputation: 7621

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.

Upvotes: 4

NotSoary
NotSoary

Reputation: 11

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

Upvotes: 1

Related Questions