aiohttp icon indicating copy to clipboard operation
aiohttp copied to clipboard

Cannot get the return from the server using ClientSession, resulting in concurrent.futures._base.TimeoutError

Open harrylyx opened this issue 5 years ago • 2 comments

Describe the bug

When I use ClientSession, sometime send post request, server has returned message, but client did not receive, then client will be TimeoutError.In each test, the number of successes is random.

To Reproduce

A Simple Server

from aiohttp import web

async def hello(request):
    data = await request.text()
    print(data)
    return web.json_response(data)


app = web.Application()
app.add_routes([web.post("/", hello)])

web.run_app(app, host="127.0.0.1", port=5000)

Client

import asyncio
import requests
from aiohttp.client import ClientSession


async def make_request(*args, **kwargs):
    async with ClientSession() as session:
        response = await session.request(
            method="post",
            url="http://127.0.0.1:5000/",
            allow_redirects=False,
            timeout=1,
            *args,
            **kwargs
        )
    return await response.json()


async def generate_aiohttp(num):
    headers = {"Content-Type": "application/json"}
    features = {"test": "test"}
    _res_json = await make_request(json={"num": num}, headers=headers)
    print(_res_json)


def generate_requests(num):
    headers = {"Content-Type": "application/json"}
    features = {"test": "test"}
    _res_json = requests.post(
        "http://127.0.0.1:5000/", json={"num": num}, headers=headers
    )
    print(_res_json.text)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    for i in range(100):
        loop.run_until_complete(generate_aiohttp(i))

    # for _ in range(100):
    #     generate_requests()

Run

First run server, python server.py Then run client, python client.py

Expected behavior

Every request should return successfully I use ClientSession, it will be TimeoutError, but I use requests.post, it will be success.

Logs/tracebacks

# server
❯ python -m tests.test_sever_bug
======== Running on http://127.0.0.1:5000 ========
(Press CTRL+C to quit)
{"num": 0}
{"num": 1}
{"num": 2}
{"num": 3}
{"num": 4}
{"num": 5}
{"num": 6}
{"num": 7}

# client
❯ python -m tests.test_client_bug
{"num": 0}
{"num": 1}
{"num": 2}
{"num": 3}
{"num": 4}
{"num": 5}
{"num": 6}
Traceback (most recent call last):
  File "/anaconda3/envs/aiohttp/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/anaconda3/envs/aiohttp/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/aiohttp/tests/test_client_bug.py", line 38, in <module>
    loop.run_until_complete(generate_aiohttp(i))
  File "/anaconda3/envs/aiohttp/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
    return future.result()
  File "/aiohttp/tests/test_client_bug.py", line 22, in generate_aiohttp
    _res_json = await make_request(json={"num": num}, headers=headers)
  File "/aiohttp/tests/test_client_bug.py", line 16, in make_request
    return await response.json()
  File "/aiohttp/aiohttp/client_reqrep.py", line 1024, in json
    await self.read()
  File "/aiohttp/aiohttp/client_reqrep.py", line 964, in read
    self._body = await self.content.read()
  File "/aiohttp/aiohttp/streams.py", line 367, in read
    block = await self.readany()
  File "/aiohttp/aiohttp/streams.py", line 389, in readany
    await self._wait("readany")
  File "/aiohttp/aiohttp/streams.py", line 310, in _wait
    await waiter
  File "/aiohttp/aiohttp/helpers.py", line 694, in __exit__
    raise asyncio.TimeoutError from None
concurrent.futures._base.TimeoutError

Python Version

$ python --version
Python 3.7.11

aiohttp Version

$ python -m pip show aiohttp
4.0.0a1

multidict Version

$ python -m pip show multidict
Name: multidict
Version: 5.2.0
Summary: multidict implementation
Home-page: https://github.com/aio-libs/multidict

yarl Version

$ python -m pip show yarl
Name: yarl
Version: 1.7.0
Summary: Yet another URL library
Home-page: https://github.com/aio-libs/yarl/

OS

macOS Big Sur 11.5.2 (20G95)

Related component

Client

Additional context

No response

Code of Conduct

  • [X] I agree to follow the aio-libs Code of Conduct

harrylyx avatar Nov 18 '21 07:11 harrylyx

There's a timeout in the aiohttp code, but not the requests code. Just to clarify, if you remove the timeout parameter from the aiohttp code, you still have the same issue?

Also, probably not related, but there are a couple of things you should probably change to be on the safe side. async with for the request, as per the documentation examples: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request Plus, use asyncio.run(), rather than dealing with the low-level asyncio API.

Dreamsorcerer avatar Nov 18 '21 19:11 Dreamsorcerer

There's a timeout in the aiohttp code, but not the requests code. Just to clarify, if you remove the timeout parameter from the aiohttp code, you still have the same issue?

Also, probably not related, but there are a couple of things you should probably change to be on the safe side. async with for the request, as per the documentation examples: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request Plus, use asyncio.run(), rather than dealing with the low-level asyncio API.

No matter how much the timeout parameter is equal to, it will eventually timeout.

I reference https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request, and modify the make_request func like this:

async def make_request(*args, **kwargs):
    async with ClientSession() as session:
        async with session.post(
            url="http://127.0.0.1:5000/", timeout=5, *args, **kwargs
        ) as resp:
            return await resp.json()

It becomes normal, Thanks.

harrylyx avatar Nov 19 '21 02:11 harrylyx