0

I'm trying to create an api, and when i try to convert the aiohttp.ClientResponse to text, my code never finishes (never go to the next line) and it raises TimeoutError, I tried to do this in terminal (with the same site), and it works, can someone help me?

Here's my current code:

async with aiohttp.ClientSession() as session:
    # _base="https://frankerfacez.com"
    # query="monka"
    # sort="count-desc"
    r = await session.get(f'{_base}/emoticons/wall?q={query}&sort={sort}')

txt = await r.text()

And it raises this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 612, in run_until_complete
    return future.result()
  File "C:\Users\Kaigo\Desktop\FFZ Api\ffz\__init__.py", line 112, in search
    txt = await r.text()
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 1009, in text
    await self.read()
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 973, in read
    self._body = await self.content.read()
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 358, in read
    block = await self.readany()
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 380, in readany
    await self._wait('readany')
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 296, in _wait
    await waiter
  File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 596, in __exit__
    raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
  • The error has nothing to do with converting a string to text. It is caused by a network timeout. If you change `txt=await r.text()` to simply `print(await r)` I expect you will get the same error. – Paul Cornelius Mar 24 '20 at 18:44
  • @PaulCornelius This isn't an network error, because r.status == 200 And it would give another error (not this one). I think –  Mar 24 '20 at 22:14

1 Answers1

3

you're trying to read from the request after clossing the session. Move the await r.text() to inside the async with block:

async with aiohttp.ClientSession() as session:
    url = f'{_base}/emoticons/wall?q={query}&sort={sort}'
    async with session.get(url) as r:
        txt = await r.text()
nosklo
  • 217,122
  • 57
  • 293
  • 297