flask plus json

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

Install jsonrpcserver to process the JSON-RPC requests:

$ pip install jsonrpcserver

Create a views.py:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from jsonrpcserver import methods

def ping():
    return 'pong'

def jsonrpc(request):
    response = methods.dispatch(request.body.decode())
    return JsonResponse(response, status=response.http_status)

Start the development server on port 5000:

$ python manage.py runserver 5000
Performing system checks...

System check identified no issues (0 silenced).
October 29, 2016 - 13:37:51
Django version 1.10.2, using settings 'mysite.settings'
Starting development server at
Quit the server with CONTROL-C.


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)