From d7c8ad3c7e2d039982ff3ff80402641b05188f8b Mon Sep 17 00:00:00 2001 From: Chow Loong Jin Date: Tue, 23 Jan 2018 18:51:06 +0800 Subject: [PATCH] Use flask.jsonify for json responses This ensures that all json responses have the correct mimetype without needing the extra boilerplate to set the content-type header. --- locust/static/locust.js | 3 +-- locust/web.py | 24 +++++++++--------------- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/locust/static/locust.js b/locust/static/locust.js index ad10fd7221..75473a1c17 100644 --- a/locust/static/locust.js +++ b/locust/static/locust.js @@ -123,8 +123,7 @@ var responseTimeChart = new LocustLineChart($(".charts-container"), "Response Ti var usersChart = new LocustLineChart($(".charts-container"), "Number of Users", ["Users"], "users"); function updateStats() { - $.get('/stats/requests', function (data) { - report = JSON.parse(data); + $.get('/stats/requests', function (report) { $("#total_rps").html(Math.round(report.total_rps*100)/100); //$("#fail_ratio").html(Math.round(report.fail_ratio*10000)/100); $("#fail_ratio").html(Math.round(report.fail_ratio*100)); diff --git a/locust/web.py b/locust/web.py index 15ca5fa056..aa31599ec4 100644 --- a/locust/web.py +++ b/locust/web.py @@ -9,7 +9,7 @@ from time import time import six -from flask import Flask, make_response, render_template, request +from flask import Flask, make_response, jsonify, render_template, request from gevent import pywsgi from locust import __version__ as version @@ -59,16 +59,12 @@ def swarm(): locust_count = int(request.form["locust_count"]) hatch_rate = float(request.form["hatch_rate"]) runners.locust_runner.start_hatching(locust_count, hatch_rate) - response = make_response(json.dumps({'success':True, 'message': 'Swarming started'})) - response.headers["Content-type"] = "application/json" - return response + return jsonify({'success': True, 'message': 'Swarming started'}) @app.route('/stop') def stop(): runners.locust_runner.stop() - response = make_response(json.dumps({'success':True, 'message': 'Test stopped'})) - response.headers["Content-type"] = "application/json" - return response + return jsonify({'success':True, 'message': 'Test stopped'}) @app.route("/stats/reset") def reset_stats(): @@ -135,22 +131,20 @@ def request_stats(): report["state"] = runners.locust_runner.state report["user_count"] = runners.locust_runner.user_count - return json.dumps(report) + return jsonify(report) @app.route("/exceptions") def exceptions(): - response = make_response(json.dumps({ + return jsonify({ 'exceptions': [ { - "count": row["count"], - "msg": row["msg"], - "traceback": row["traceback"], + "count": row["count"], + "msg": row["msg"], + "traceback": row["traceback"], "nodes" : ", ".join(row["nodes"]) } for row in six.itervalues(runners.locust_runner.exceptions) ] - })) - response.headers["Content-type"] = "application/json" - return response + }) @app.route("/exceptions/csv") def exceptions_csv():