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

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

@Request.application
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)

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'