asyncio
has been included into standard library 2
years ago, in Python 3.4
asyncio
: Python 3.3asyncio
has been ported to Python 2 as
trollius
yield from
import asyncio
import random
@asyncio.coroutine
def hello_world(idx):
yield from asyncio.sleep(random.uniform(.1, .5))
print('Hello, world!', idx)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([hello_world(idx) for idx in range(10)]))
loop.close()
Hello, world! 2
Hello, world! 9
Hello, world! 4
Hello, world! 5
Hello, world! 1
Hello, world! 3
Hello, world! 8
Hello, world! 7
Hello, world! 6
Hello, world! 0
import random
import time
def hello_world(idx):
time.sleep(random.uniform(.1, .5))
print('Hello, world!', idx)
[hello_world(idx) for idx in range(10)]
Hello, world! 0
Hello, world! 1
Hello, world! 2
Hello, world! 3
Hello, world! 4
Hello, world! 5
Hello, world! 6
Hello, world! 7
Hello, world! 8
Hello, world! 9
import asyncio
@asyncio.coroutine
yield from asyncio.sleep(...)
loop = asyncio.get_event_loop()
asyncio.wait([...])
loop.run_until_complete(...)
loop.close()
yield from
is so 1998@asyncio.coroutine
def hello_world(idx):
yield from asyncio.sleep(random.uniform(.1, .5))
print('Hello, world!', idx)
async def hello_world(idx):
yield from asyncio.sleep(random.uniform(.1, .5))
print('Hello, world!', idx)
async def hello_world(idx):
await asyncio.sleep(random.uniform(.1, .5))
print('Hello, world!', idx)
with (yield from engine) as conn:
yield from conn.excute(...)
async with engine.acquire() as conn:
await conn.execute(...)
for item in (yield from conn.execute(...)):
...
async for item in conn.execute(...):
...
pip install uvloop
gunicorn -b 0.0.0.0:8000 -k aiohttp.worker.GunicornUVLoopWebWorker -w 5 \
path.to.app:app
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def run():
conn = await asyncpg.connect(user='user', password='password',
database='database', host='127.0.0.1')
values = await conn.fetch('SELECT * FROM mytable')
await conn.close()
fatoptimizer
projectfat
module