简体   繁体   中英

Flask's jsonify function inconsistent with flask-marshmallow

I am developing an API using flask-RESTful and am having an issue with Flask's jsonify function. I am using flask-marshmallow for JSON serialization. Below is a very simplified code snippet:

result = activities_schema.dump(activities)
return jsonify(result)

Locally, the endpoint will return json that has keys 'data' and 'errors'; however, when running on a Linux server, this returns a result that contains a list and a dict, without the 'data' and 'errors' keys.

I have determined this inconsistency is caused by Flask's jsonify function by printing out results before they are returned by the API. Both locally and on the server, 'result' equals:

MarshalResult(data=[], errors={})

However, when I print the response after using Flask's jsonify, I get this locally:

('{\n  "data": [], \n  "errors": {}\n}', '\n')

while this is printed on the server:

('[\n  [], \n  {}\n]', '\n')

Anyone know why these don't match?

I researched some more, and found one solution to the problem (I feel a bit silly since the solution is right in the docs), but cannot explain why the original problem happens.

The solution (found here ) is to either use:

jsonify(result.data)

or:

activities_schema.jsonify(result)

Either method will return just the data, not the errors.

I still cannot explain why doing it the other way was inconsistent between the server and my local machine, but maybe that's a different question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM