How to use JSON-RPC with Django?

flask json

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

Install Django and Jsonrpcserver to process the JSON-RPC requests:

pip install django jsonrpcserver

Create a

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from jsonrpcserver import method, Result, Success, dispatch

def ping() -> Result:
    return Success("pong")

def jsonrpc(request):
    return HttpResponse(
        dispatch(request.body.decode()), content_type="application/json"

Start the development server on port 5000:

$ python 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.

Test it

$ curl -X POST http://localhost:5000 -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}'
{"jsonrpc": "2.0", "result": "pong", "id": 1}