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 views.py:

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


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


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

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 http://127.0.0.1:5000/
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}