Skip to content

Commit

Permalink
Merge pull request ccxt#3595 from CoinVantage/py-async-with
Browse files Browse the repository at this point in the history
Python: Add support for async context manager to auto-close connections
  • Loading branch information
kroitor authored Aug 11, 2018
2 parents 0755add + e5a4ecb commit c72f3c5
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions python/ccxt/async_support/base/exchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import certifi
import aiohttp
import ssl
import sys
import yarl

# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -49,12 +50,7 @@ def __init__(self, config={}):
self.asyncio_loop = config['asyncio_loop']
self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop()
self.own_session = 'session' not in config
if self.own_session:
# Create our SSL context object with our CA cert file
context = ssl.create_default_context(cafile=certifi.where())
# Pass this SSL context to aiohttp and create a TCPConnector
connector = aiohttp.TCPConnector(ssl_context=context, loop=self.asyncio_loop)
self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector)
self.open()
super(Exchange, self).__init__(config)
self.init_rest_rate_limiter()

Expand All @@ -67,6 +63,22 @@ def __del__(self):
if self.session is not None:
self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are creating the exchange instance from within your async coroutine, add exchange.close() to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).")

if sys.version_info >= (3, 5):
async def __aenter__(self):
self.open()
return self

async def __aexit__(self, exc_type, exc, tb):
await self.close()

def open(self):
if self.own_session and self.session is None:
# Create our SSL context object with our CA cert file
context = ssl.create_default_context(cafile=certifi.where())
# Pass this SSL context to aiohttp and create a TCPConnector
connector = aiohttp.TCPConnector(ssl_context=context, loop=self.asyncio_loop)
self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector)

async def close(self):
if self.session is not None:
if self.own_session:
Expand Down

0 comments on commit c72f3c5

Please sign in to comment.