I have the following flak_restful file to return back a csv file to the user, but I'm getting the following error.
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'Response' is not JSON serializable
import flask
from flask import request
from flask_restful import Resource
class MyAPIRes(Resource):
@classmethod
def get(cls):
csv = '1,2,3\n4,5,6\n'
response = flask.make_response(csv)
response.headers['content-type'] = 'application/octet-stream'
return response, 200
Removing the , 200
from the second part of the return statement should work.
That second argument will call a helper from flask_restful
to create a response, but in this case, you've already gone ahead and created a response object with make_response
. That's fine, you need to create your own object to return anything other than JSON. But one of the things the helper does is serialize your data for you (turn it into JSON), and the Response
type is not serializable.
Taking a look at the trace, you can see it happening in the error message here:
File ".../flask_restful/__init__.py", line 510, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)
File ".../flask_restful/representations/json.py", line 20, in output_json
dumped = dumps(data, **settings) + "\n"
Docs on response types can be found in the section on flask_restful
response formats.