Why is flask jsonify method slow?

I am writing an API in a flask that returns json. Each bulb function has the form

from flask import jsonify @app.route('/getdata') def get_data(): data = load_data_as_dict() return jsonify(data) 

If I return a large amount of data, calling this function will take about 1.7 seconds. However, if I do this:

 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" 

... the function completes in about 0.5 seconds.

Can someone tell me why jsonify so much slower? Is there anything wrong with returning the original response to the flask instead?

Thanks!

+7
performance json python api flask
source share
2 answers

I guess it has a lot to do with indenting and dumping pretty json. Here's the definition of the method (I split the comments to save space, the full code can be found here ):

 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 wraps simplejson.dumps if the module is available, otherwise it uses json.dumps .

What performance will you get if you run your code with the same arguments?

+5
source share

The documentation says that:

This function wraps dumps () to add a few enhancements that make life easier. It turns JSON output into a Response object with application / json mimetype.

Thus, it does the same thing, you get a Reponse object in both cases , but since it is a convenient function, it probably works more than lightweight, which means extra time.

EDIT: actually looking again at the docs:

For clarity, the behavior of JSON serialization has the following differences from dumps (): The only argument: Passed directly to dumps ().

Can you check both return jsonify(data) and return json.dumps(data) ? They must match.

0
source share

All Articles