Skip to content

Commit

Permalink
Recreate sessin if loop is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
Max Zheng committed Mar 23, 2018
1 parent 153c55d commit c0a613b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 10 additions & 2 deletions aiohttp_requests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,21 @@ def __init__(self, *args, **kwargs):
@property
def session(self):
""" An instance of aiohttp.ClientSession """
if not self._session or self._session.closed:
if not self._session or self._session.closed or self._session.loop.is_closed():
self._session = aiohttp.ClientSession(*self._session_args[0], **self._session_args[1])
return self._session

def __getattr__(self, attr):
if attr.upper() in aiohttp.hdrs.METH_ALL:
return functools.partial(self.session._request, attr.upper())
@functools.wraps(self.session._request)
def session_request(*args, **kwargs):
"""
This ensures `self.session` is always called where it can check the session/loop state so can't use functools.partials
as monkeypatch seems to do something weird where __getattr__ is only called once for each attribute after patch is undone
"""
return self.session._request(attr.upper(), *args, **kwargs)

return session_request
else:
return super().__getattribute__(attr)

Expand Down
2 changes: 2 additions & 0 deletions tests/test_aiohttp_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ async def test_aiohttp_requests_integration():


async def test_aiohttp_requests_after_close(loop):
# Closing ourself
requests.close()

await test_aiohttp_requests_integration()

# Closing aiohttp session
await requests.session.close()

await test_aiohttp_requests_integration()

0 comments on commit c0a613b

Please sign in to comment.