flask plus json

We’ll use Flask to take JSON-RPC requests. It should respond to “ping” with “pong”.

Install Flask to take requests and jsonrpcserver to process them:

$ pip install flask jsonrpcserver

Create a server.py:

from flask import Flask, request, Response
from jsonrpcserver import method, dispatch

app = Flask(__name__)

@method
def ping():
    return "pong"

@app.route("/", methods=["POST"])
def index():
    req = request.get_data().decode()
    response = dispatch(req)
    return Response(str(response), response.http_status, mimetype="application/json")

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

Start the server:

$ python server.py
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 216-262-392

Client

Use jsonrpcclient to send requests:

$ pip install "jsonrpcclient[requests]"
$ python
>>> from jsonrpcclient import request
>>> request("http://localhost:5000/", "ping").data.result
'pong'