werkzeug plus json

We’ll use Werkzeug to take JSON-RPC requests. It should respond to ‘ping’ with ‘pong’.

Install Werkzeug to take requests and jsonrpcserver to process them:

$ pip install werkzeug jsonrpcserver

Create a server.py:

from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from jsonrpcserver import methods

def ping():
    return 'pong'

def application(request):
    r = methods.dispatch(request.data.decode())
    return Response(str(r), r.http_status, mimetype='application/json')

if __name__ == '__main__':
    run_simple('localhost', 5000, application)

Start the server:

$ python server.py
 * Running on http://localhost:5000/ (Press CTRL+C to quit)


Use jsonrpcclient to send requests:

$ pip install 'jsonrpcclient[requests]'
$ python
>>> import jsonrpcclient
>>> jsonrpcclient.request('http://localhost:5000/', 'ping')
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1} (200 OK)