diff --git a/CHANGES.rst b/CHANGES.rst index 333a71b3543..e76b53766c6 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -45,7 +45,7 @@ CHANGES - Allow to raise web exceptions on router resolving stage #1460 -- +- Add a warning for session creation outside of coroutine #1468 - diff --git a/aiohttp/client.py b/aiohttp/client.py index 6c5d02944dc..4b498746421 100644 --- a/aiohttp/client.py +++ b/aiohttp/client.py @@ -54,6 +54,17 @@ def __init__(self, *, connector=None, loop=None, cookies=None, if loop.get_debug(): self._source_traceback = traceback.extract_stack(sys._getframe(1)) + if not loop.is_running(): + warnings.warn("Creating a client session outside of coroutine is " + "a very dangerous idea", ResourceWarning, + stacklevel=2) + context = {'client_session': self, + 'message': 'Creating a client session outside ' + 'of coroutine'} + if self._source_traceback is not None: + context['source_traceback'] = self._source_traceback + loop.call_exception_handler(context) + if cookie_jar is None: cookie_jar = CookieJar(loop=loop) self._cookie_jar = cookie_jar diff --git a/tests/test_client_session.py b/tests/test_client_session.py index 74e0c07a85b..e51fe78f468 100644 --- a/tests/test_client_session.py +++ b/tests/test_client_session.py @@ -435,3 +435,9 @@ def test_proxy_str(session, params): allow_redirects=True, proxy='http://proxy.com', **params)] + + +def test_create_session_outside_of_coroutine(loop): + with pytest.warns(ResourceWarning): + sess = ClientSession(loop=loop) + sess.close()