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 methods

app = Flask(__name__)

@methods.add
def ping():
    return 'pong'

@app.route('/', methods=['POST'])
def index():
    req = request.get_data().decode()
    response = methods.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.http_client import HTTPClient
>>> HTTPClient('http://localhost:5000/').request('ping')
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1} (200 OK)
'pong'