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 import method, async_dispatch as dispatch

async def ping():
    return "pong"

async def handle(request):
    request = await request.text()
    response = await dispatch(request)
    if response.wanted:
        return web.json_response(response.deserialized(), status=response.http_status)
        return web.Response()

app = web.Application()
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 import request
>>> request("http://localhost:5000/", "ping").data.result

Asynchronous client with aiohttp

$ pip install "jsonrpcclient[aiohttp]"

Create a client.py:

import aiohttp
import asyncio
from jsonrpcclient.clients.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