asyncio

Gael Pasgrimaud @gawel_

python-nantes 2015

About me

Quoi c’est ?

Historique

BDFL want async

=> tulip => python3.4 asyncio

Comment que c’est ?

Exemple

Une simple requete http:

import requests

print(requests.get('http://python.org'))

Et avec asyncio...

import asyncio
import aiohttp


@asyncio.coroutine
def fetch_page(url):
    response = yield from aiohttp.request('GET', url)
    assert response.status == 200
    return (yield from response.read())

content = asyncio.get_event_loop().run_until_complete(
    fetch_page('http://python.org'))
print(content)

Event loop

Future

import asyncio

loop = asyncio.get_event_loop()


@asyncio.coroutine
def get_future():
    future = asyncio.Future()
    loop.call_later(2, future.set_result)
    return future

loop.run_until_complete(get_future())

Task

t = asyncio.Task(coro)
t.add_done_callback(func)

Outils

Protocol

import asyncio


class EchoClient(asyncio.Protocol):

    def connection_made(self, transport):
        print('connection_made')
        self.transport = transport
        self.host, self.port = transport.get_extra_info('peername')

    def data_received(self, data):
        """hook to handle data received by sock.recv()"""
        # write data to socket. try to send directly else create a buffer
        self.transport.write(data)

    def connection_lost(self, exc):
        print('closed')

Connection / Server

import asyncio
from myapp import EchoClient
from myapp import EchoServer

loop = asyncio.get_event_loop()


@asyncio.coroutine
def run_client():
    protocol, transport = yield from loop.create_connection(EchoClient,
                                                            '127.0.0.1', 8000)
    loop.call_later(5, transport.close)

@asyncio.coroutine
def run_server():
    server = yield from loop.create_Server(EchoServer, '127.0.0.1', 8000)
    loop.create_task(run_client())

loop.run_forever()

Cas d’utilisation

Ecosystème