Skip to content

Instantly share code, notes, and snippets.

@akhoronko
Last active June 19, 2017 15:12
Show Gist options
  • Save akhoronko/a653e12e285c9cc8a9faa96d92556f98 to your computer and use it in GitHub Desktop.
Save akhoronko/a653e12e285c9cc8a9faa96d92556f98 to your computer and use it in GitHub Desktop.
import os
import socket
import asyncio
from aio_pika import connect, Connection
from yarl import URL
AMQP_URL = URL(os.getenv("AMQP_URL", "amqp://guest:guest@localhost"))
if not AMQP_URL.path:
AMQP_URL.path = '/'
async def main(loop):
client = await connect(AMQP_URL, loop=loop)
print('connected')
f = loop.create_future()
def on_close(fut):
nonlocal f
exc = fut.exception()
print('on_close exception:', exc)
f.set_result(True)
client.add_close_callback(on_close)
# 'is_closed' uses 'closing' property which copy client's closing future
# and in case of connection's exception this future exception won't be consumed -
# 'Future exception was never retrieved' will be printed
print('is_closed', client.is_closed)
# exception won't be consumed as it described above
channel = await client.channel()
# break connection
client._connection.socket.shutdown(socket.SHUT_RDWR)
await f
print('finished')
client = CustomConnection(
host=AMQP_URL.host,
port=AMQP_URL.port,
login=AMQP_URL.user,
password=AMQP_URL.password,
virtual_host=AMQP_URL.path,
loop=loop
)
await client.connect()
print('connected new client')
f = loop.create_future()
client.add_close_callback(on_close)
print('is_closed', client.is_closed)
client._connection.socket.shutdown(socket.SHUT_RDWR)
await f
print('finished')
class CustomConnection(Connection):
@property
def is_closed(self):
""" Is this connection are closed """
if not (self._connection and self._connection.socket):
return True
if self._closing.done(): # changed line
return True
return False
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
@akhoronko
Copy link
Author

output:

connected
is_closed False
on_close exception: [Errno Not specified] 0
Future exception was never retrieved
future: <Future finished exception=ConnectionError('Not specified', 0)>
ConnectionError: [Errno Not specified] 0
Future exception was never retrieved
future: <Future finished exception=ConnectionError('Not specified', 0)>
ConnectionError: [Errno Not specified] 0
finished
connected new client
is_closed False
on_close exception: [Errno Not specified] 0
finished

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment