Skip to content

Commit

Permalink
Add support for context-managers
Browse files Browse the repository at this point in the history
By implementing (a)enter/(a)exit internal methods, we bring the support
for context-managers in the base.Consul object.

Context managers are quite convenient, especially for the aio implementation
in which you may need a good control over objects lifecycle to prevent
errors related to already-closed event loops:

This is done by forcing http implementations to define a close method.
Most of the synchronous implementations will use a noop.

```
async with aio.Consul(...) as consul:
  svcs = consul.agent.services()
  # Implicit close of the HTTP client

```
  • Loading branch information
pierrecdn committed Dec 21, 2020
1 parent f334e05 commit 71b37e7
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
16 changes: 16 additions & 0 deletions consul/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,10 @@ def delete(self, callback, path, params=None):
def post(self, callback, path, params=None, data=''):
raise NotImplementedError

@abc.abstractmethod
def close(self):
raise NotImplementedError


class Consul:
def __init__(
Expand Down Expand Up @@ -345,6 +349,18 @@ def __init__(
self.operator = Consul.Operator(self)
self.connect = Consul.Connect(self)

def __enter__(self):
return self

async def __aenter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.http.close()

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

class Event:
"""
The event command provides a mechanism to fire a custom user event to
Expand Down
3 changes: 3 additions & 0 deletions consul/std.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ def post(self, callback, path, params=None, data=''):
self.session.post(uri, data=data, verify=self.verify,
cert=self.cert)))

def close(self):
pass


class Consul(base.Consul):
@staticmethod
Expand Down
3 changes: 3 additions & 0 deletions consul/tornado.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ def post(self, callback, path, params=None, data=''):
validate_cert=self.verify)
return self._request(callback, request)

def close(self):
self.client.close()


class Consul(base.Consul):
@staticmethod
Expand Down
4 changes: 4 additions & 0 deletions consul/twisted.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ def delete(self, callback, path, params=None):
response = yield self.request(callback, 'delete', uri, params=params)
returnValue(response)

@inlineCallbacks
def close(self):
pass


class Consul(base.Consul):
@staticmethod
Expand Down

0 comments on commit 71b37e7

Please sign in to comment.