MagicStack / uvloop

Ultra fast asyncio event loop.
Apache License 2.0
10.44k stars 548 forks source link

uvloop + aiohttp RuntimeError: Timeout context manager should be used inside a task #63

Closed superstarrr closed 7 years ago

superstarrr commented 7 years ago

Hi guys,

My program runs normally when using default asyncio policy. But if installing the uvloop event loop policy,

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

the following exception will be raised:

Traceback (most recent call last):
  File "/opt/venv/websec/lib/python3.5/site-packages/aiohttp/client.py", line 565, in __aenter__
    self._resp = yield from self._coro
  File "/opt/venv/websec/lib/python3.5/site-packages/aiohttp/client.py", line 197, in _request
    with Timeout(timeout, loop=self._loop):
  File "/opt/venv/websec/lib/python3.5/site-packages/async_timeout/__init__.py", line 33, in __enter__
    raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task

Thanks!

1st1 commented 7 years ago

This is strange, I don't see how this can happen. Could you please share the code so that I can debug this?

superstarrr commented 7 years ago

Finally I figure it out, it is caused by the incorrect position of installing code.

The installing code is put under one imported module which creates an instance of aiohttp.ClientSession(), for example,

# main.py
import asyncio

from foo import Foo

import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

async def fetch(url):
    foo = Foo()
    async with foo.session.get(url) as resp:
        # RuntimeError will be raised here
        pass

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch('http://example.com'))

# foo.py
import aiohttp

class Foo():
    session = aiohttp.ClientSession()    # to share session between instances of Foo
asvetlov commented 7 years ago

Hrrr.

You are creating a global var here (class variable actually). It is anti-pattern with very bad smell.

superstarrr commented 7 years ago

I have to admit that it is a bad idea. And will remove these lazy code. Thanks!

1st1 commented 7 years ago

Should this issue be closed now?

1st1 commented 7 years ago

OK, closing this.