我在flask中编写了一个返回JSON的API。每个烧瓶的功能都是这样的
from flask import jsonify
@app.route('/getdata')
def get_data():
data = load_data_as_dict()
return jsonify(data)
如果返回大量数据,则调用此函数大约需要1.7秒。但是,如果我这样做:
from flask import Response
@app.route('/getdata')
def get_data():
data = load_data_as_dict()
data_as_str = json.dumps(data)
return Response(response=data_as_str, status=200, mimetype="application/json"
…功能在0.05秒左右完成。
有人能告诉我为什么
jsonify
慢得多吗?返回未加工的烧瓶响应有什么问题吗? 最佳答案
我的猜测是:这与缩进和生成一个pretty
json转储有很大的关系。下面是方法定义(我去掉注释以节省空间,可以找到完整的代码)。
def jsonify(*args, **kwargs):
indent = None
separators = (',', ':')
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
indent = 2
separators = (', ', ': ')
if args and kwargs:
raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
elif len(args) == 1: # single args are passed directly to dumps()
data = args[0]
else:
data = args or kwargs
return current_app.response_class(
(dumps(data, indent=indent, separators=separators), '\n'),
mimetype=current_app.config['JSONIFY_MIMETYPE']
)
如果模块可用,
dumps
wrappssimplejson.dumps
关于python - 为什么 flask 的jsonify方法很慢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37931927/