Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is flask's jsonify method slow?

I'm writing an API in flask that returns json. Each flask function is of 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, a call to this function takes around 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 around .05 seconds.

Can anyone tell me why jsonify is so much slower? Is there anything wrong with returning a raw Flask response instead?

like image 440
diego_c Avatar asked Jun 20 '16 21:06

diego_c


People also ask

Why do flasks take long to load?

When Flask app runs slow we need to identify what is the bottleneck. It can be an overloaded database, unresponsive external API, or heavy, CPU-intensive computation. This is the whole recipe on how to speed up Flask - find the source of sluggish performance.

What does Flask's Jsonify ()` do?

Flask jsonify is defined as a functionality within Python's capability to convert a json (JavaScript Object Notation) output into a response object with application/json mimetype by wrapping up a dumps( ) function for adding the enhancements.

What is the difference between Jsonify and json dumps?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.


1 Answers

My guess is: it has a lot to do with indentation and making a pretty json dump. Here's the method definition (I stripped the comments to save space, 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.

like image 88
kardaj Avatar answered Oct 23 '22 13:10

kardaj