async/await

asyncio required that all generators meant to be used as a coroutine had to be decorated with asyncio.coroutine.

@asyncio.coroutinedefpy34_coroutine():yield fromavaitable()

Since Python 3.5 native coroutines are their own completely distinct type, before they were just enhanced generators. async syntax makes coroutines a native Python language feature, and clearly separates them from generators.

async def py35_coroutine():
await avaitable()

Features:

async def functions are always coroutines, even if they do not contain await expressions

It is a SyntaxError to have yield or yield from expressions in an async function

It is a SyntaxError to use await outside of an async def function (like it is a SyntaxError to use yield outside of def function)

It is a TypeError to pass anything other than an awaitable object to an await expression

await expressions do not require parentheses around them most of the times

async for, async with

Support for asynchronous calls is limited to expressions where yield is allowed syntactically, limiting the usefulness of syntactic features, such as with and for statements (PEP 492).

The new async with statement lets Python programs perform asynchronous calls when entering and exiting a runtime context, and the new async for statement makes it possible to perform asynchronous calls in iterators. An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.

aiopg

aioamqp

Retries:

importloggingimporttimeimportasyncioimportaioamqpRETRY_DELAY=(1,2,4,8,30,60)logger=logging.getLogger(__name__)channel=Noneasyncdefconsumer(channel,body,envelope,properties):print(body)awaitchannel.basic_client_ack(delivery_tag=envelope.delivery_tag)asyncdefconnect():transport,protocol=awaitaioamqp.connect(host='localhost',port=5672,login='guest',password='guest',virtualhost='/')channel=awaitprotocol.channel()awaitchannel.queue_declare(queue_name='test',durable=True)awaitchannel.basic_consume(consumer,queue_name='test')returnprotocol,channelasyncdefmain():globalchannelretry=0whileTrue:retry+=1start=time.time()try:protocol,channel=awaitconnect()# https://github.com/Polyconseil/aioamqp/issues/65#issuecomment-301737344awaitprotocol.wait_closed()channel=Nonelogger.warning("Channel was closed unexpectedly.")exceptOSError:logger.warning("Connection attempt failed.")iftime.time()-start>RETRY_DELAY[-1]*2:# if we got connection and lost itretry=1try:delay=RETRY_DELAY[retry-1]exceptIndexError:delay=RETRY_DELAY[-1]logger.warning("Retry in {} seconds ...".format(delay))awaitasyncio.sleep(delay)if__name__=='__main__':loop=asyncio.get_event_loop()try:loop.run_until_complete(main())finally:ifchannel:loop.run_until_complete(channel.close())logger.warning("Connection closed in a clean way.")