flask plus json

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

Install aiohttp to take requests and jsonrpcserver to process them:

$ pip install aiohttp jsonrpcserver

Create a server.py:

from aiohttp import web
from jsonrpcserver.aio import methods

app = web.Application()

async def ping():
    return 'pong'

async def handle(request):
    request = await request.text()
    response = await methods.dispatch(request)
    return web.json_response(response)

app.router.add_post('/', handle)

if __name__ == '__main__':
    web.run_app(app, port=5000)

Start the server:

$ python server.py
======== Running on ========
(Press CTRL+C to quit)

Synchronous 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)

Asynchronous client with aiohttp

$ pip install 'jsonrpcclient[aiohttp]'

Create a client.py:

import aiohttp
import asyncio
from jsonrpcclient.aiohttp_client import aiohttpClient

async def main(loop):
    async with aiohttp.ClientSession(loop=loop) as session:
        client = aiohttpClient(session, 'http://localhost:5000/')
        response = await client.request('ping')

loop = asyncio.get_event_loop()
$ python client.py
--> {"jsonrpc": "2.0", "method": "ping", "id": 1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1}