On Mon, Dec 14, 2020 at 4:57 AM Ethan Furman <et...@stoneleaf.us> wrote: > > From: Caleb Gattegno > Date: Fri, Dec 11, 2020 at 5:02 PM > Subject: How to specify JSON parameters in CallBack? > > > Please can you suggest where should I look for advice on converting a old > style web app which vends whole pages of html > with a cgi-bin/python script invoked bypython3 server.py, into one that only > serves callbacks to this Javascript AJAX > async RPC call: > > $('#compute').click(function() { > $('#poly').val('Waiting...'); > > var seq = $('#seq').val(); > console.log(seq); > $.post('/compute', seq, function(result) { > $('#poly').val(result.poly); > }, 'json'); > }); > > I don’t want to touch the html/javascript, but I’d like to update the python > cgi code module to respond to the RPC call > in the post by returning a json data structure. Poly is a string of variable > length. >
First place to look would be a well-known server framework. I use Flask, but there are others. Figure out exactly what your front end is sending; use your web browser's developer tools to inspect the requests, and then code your back end to match. Writing a JSON-based API in Flask is pretty straight-forward. Here's an example: @app.route("/api/widgets") def list_setups(): return jsonify(database.list_widgets()) @app.route("/api/widgets/<int:id>") def get_widget(id): return jsonify(database.get_widget(id)) @app.route("/api/widgets", methods=["POST"]) def create_widget(): if not request.json: return jsonify({}), 400 missing = {"name", "purpose"} - set(request.json) if missing: return jsonify({"error": "Missing: " + ", ".join(sorted(missing))}), 400 widget = database.create_widget(request.json["name"], request.json["purpose"]) return jsonify(widget) (For a real example, see https://github.com/Rosuav/MustardMine/blob/master/mustard.py#L643 - although that has a lot of other complexities.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list