简体   繁体   English

Flask 的 jsonify 函数与flask-marshmallow 不一致

[英]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.我正在使用 Flask-RESTful 开发 API,并且 Flask 的 jsonify 函数有问题。 I am using flask-marshmallow for JSON serialization.我正在使用烧瓶棉花糖进行 JSON 序列化。 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';在本地,端点将返回具有键 'data' 和 'errors' 的 json; however, when running on a Linux server, this returns a result that contains a list and a dict, without the 'data' and 'errors' keys.然而,当在 Linux 服务器上运行时,这会返回一个结果,其中包含一个列表和一个字典,没有 'data' 和 'errors' 键。

I have determined this inconsistency is caused by Flask's jsonify function by printing out results before they are returned by the API.我已经确定这种不一致是由 Flask 的 jsonify 函数引起的,方法是在 API 返回结果之前打印结果。 Both locally and on the server, 'result' equals:在本地和服务器上,'result' 等于:

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

However, when I print the response after using Flask's jsonify, I get this locally:但是,当我在使用 Flask 的 jsonify 后打印响应时,我在本地得到了这个:

('{\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.我仍然无法解释为什么在服务器和我的本地机器之间以另一种方式执行它是不一致的,但也许这是一个不同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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