Search code examples
pythonaiohttp

aiohttp posting list of jsons


I saw in somebody's code that they are posting a list of requests in one aiohttp post call, and expecting to receive list of responses back. I have tried that myself and it worked (if you are curious what I'm requesting, those are blocks of Ethereum, I'm talking to a live node):

def aiohttp_test():
    import aiohttp
    import asyncio

    async def post_test():
        req = list()
        for ind, i in enumerate(range(15544190, 15544192)):
            req.append({"jsonrpc": "2.0", "id": ind + 1, "method": "eth_getBlockByNumber", "params": [hex(i), False]})

        async with aiohttp.ClientSession() as session:
            async with session.post('http://ubuntu18-1:8545', json=req) as resp:
                print(resp.status)
                print(await resp.text())

    loop = asyncio.get_event_loop()
    loop.run_until_complete(post_test())

and I actually got a list with two responses, however status is a single number 200. How is this possible? Documentation for aiohttp never mentions possibility of posting a list.


Solution

  • You are not making multiple requests. You are only making one request with a list of dicts as the json data being sent in that request. As you can see in the request reference (which is what post uses under the hood):

    • json – Any json compatible python object (optional). json and data parameters could not be used at the same time.

    You are getting one response back because of it being only one request. The status code is 200 because it was a succesful request.