-1

I am working on a webapp. I am running a python script and it collects some data now I want json dump of that data and pass it to a Flask webapp route. somthing like this route http://127.0.0.1:5000/data

I know how to json dump in a python but I am new to Flask. I want to use json.dump not jsonify. I guess something like

@app.route('/data', methods=['POST'])
def data():
  #some way to get the data and return it to the page

. I am not able to understand much from the links given below.

Please tell me how to do it.

anonghost
  • 17
  • 8
  • 1
    [How to return json using Flask web framework](http://stackoverflow.com/q/13081532), [json.dumps vs flask.jsonify](http://stackoverflow.com/q/7907596), http://flask.pocoo.org/docs/0.10/patterns/jquery/#json-view-functions, http://flask.pocoo.org/docs/0.10/api/#module-flask.json – Martijn Pieters Sep 02 '14 at 16:37
  • possible duplicate of [How to return json using Flask web framework](http://stackoverflow.com/questions/13081532/how-to-return-json-using-flask-web-framework) – codegeek Sep 02 '14 at 17:44

1 Answers1

0

Assuming you have already installed flask (pip install flask), you may achieve what you want with a simple flask server app, here referenced as server.py:

    from flask import Flask, jsonify
    app = Flask(__name__)

    @app.route("/data")
    def data_route():
        collected_data = [] # Your data
        return jsonify(results=collected_data)

    if __name__ == "__main__":
        app.run()

You should load your data into collected_data (I've used an empty list [] just as an example), by reading a file where you stored the results or by doing whatever computation you need.

Also, consider having your 'data collection script' running separately from the flask server, specially if it is computationally expensive, slow, or if the resulting data does change all the time:

  1. If your collection script returns the same results over and over, consider caching it. You may store it in many ways, but depending on your needs dumping the results to a simple file every time it runs, and serving the file contents through flask may be enough.
  2. If the resulting data is very big, you should take a look at how to stream content
rhlobo
  • 1,286
  • 9
  • 10
  • any way to do it with json.dumps() ? – anonghost Sep 02 '14 at 17:30
  • I do not see why you would want to use it, because it already sets the response type, but yes, instead of `return jsonify(results=collected_data)` you could `from flask import Response` and use `return Response(json.dumps(collected_data), mimetype='application/json')`. – rhlobo Sep 03 '14 at 13:29