Search code examples
pythonjsonflaskflask-restful

My Flask Api tries to get form data, but it is not building a Dict correctly


I have an object i create on the front end:

var data = {id:1, type:13, name:"foo", isReadonly: True};
$.ajax({
  method: "post",
  contentType: "application/json",
  data: {filename:f, json:data}
});

When I get to my python I have as follows:

class Process(Resource):
  def get(self):
    pass

  def post(self):
    data = request.form.to_dict()
    print "Raw: %s" % data
    print "Filename: %s" % data["filename"]
    print "Dataset: %s" % data["json"]
    return data["json"]

api.add_resource(Process, "/process")

When looking at the result for dataset, it changed around my keys. So now I get:

"json[id]" : 1

Ideally, im trying to turn this into a json object I can reference.. but i will get a key error if i try to do: data["json"] because json doesnt exist, so it will throw an exception.

I also tried: data = request.get_json() and data = request.get_json(force=True) and those dont seem to work either.

How can i set a variable to my json map so i can pass it into followon functions? I feel it just isnt parsed correctly, or isnt doing a deep parse.

Edit I tried to stringify the data as well, and do request.get_json() but it will return none if i try to print it.


Solution

  • You need stringify the data and use get_json(). A mini work example:

    index.html:

    <html>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
        var data = {id:1, type:13, name:"foo", isReadonly: true};
        var f = "hello.py";
        var url = "/hello"
        $.ajax({
          url: url,
          method: "post",
          contentType: "application/json",
          data: JSON.stringify({filename:f, json:data}),
        });
      </script>
    </html>
    

    app.py:

    from flask import Flask, request, jsonify
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        with open('index.html') as fp:
            return fp.read()
    
    
    @app.route('/hello', methods=['POST'])
    def hello():
        data = request.get_json()
        print("Raw: %s" % data)
        print("Filename: %s" % data["filename"])
        print("Dataset: %s" % data["json"])
        return jsonify(data["json"])
    
    
    if __name__ == '__main__':
        app.run()
    

    run and visit http://127.0.0.1:5000/:

    $ python app.py
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    127.0.0.1 - - [24/May/2017 20:38:21] "GET / HTTP/1.1" 200 -
    Raw: {'json': {'type': 13, 'name': 'foo', 'isReadonly': True, 'id': 1}, 'filename': 'hello.py'}
    Filename: hello.py
    Dataset: {'type': 13, 'name': 'foo', 'isReadonly': True, 'id': 1}
    127.0.0.1 - - [24/May/2017 20:38:22] "POST /hello HTTP/1.1" 200 -