Upgrade to Pro — share decks privately, control downloads, hide ads and more …

import asyncio

import asyncio

Brněnské Pyvi, 2014-01-30

Petr Viktorin

January 30, 2014
Tweet

More Decks by Petr Viktorin

Other Decks in Programming

Transcript

  1. Compare: web frameworks Flask app Pyramid debug toolbar Cherrypy logging

    PEP 333 - Python Web Server Gateway Interface
  2. Callback style import asyncio def print_and_repeat(loop): print('Hello World') loop.call_later(2, print_and_repeat,

    loop) loop = asyncio.get_event_loop() loop.call_soon(print_and_repeat, loop) loop.run_forever()
  3. Couroutines & Tasks import asyncio @asyncio.coroutine def greet_every_two_seconds(): while True:

    print('Hello World') yield from asyncio.sleep(1) print('How are you?') yield from asyncio.sleep(1) loop = asyncio.get_event_loop() loop.run_until_complete(greet_every_two_seconds())
  4. Echo client import asyncio class EchoClient(asyncio.Protocol): message = 'This is

    the message. It will be echoed.' def connection_made(self, transport): transport.write(self.message.encode()) print('data sent: {}'.format(self.message)) def data_received(self, data): print('data received: {}'.format(data.decode())) def connection_lost(self, exc): print('server closed the connection') asyncio.get_event_loop().stop() loop = asyncio.get_event_loop() coro = loop.create_connection(EchoClient, '127.0.0.1', 8888) loop.run_until_complete(coro) loop.run_forever() loop.close()
  5. Echo server import asyncio class EchoServer(asyncio.Protocol): def connection_made(self, transport): peername

    = transport.get_extra_info('peername') print('connection from {}'.format(peername)) self.transport = transport def data_received(self, data): print('data received: {}'.format(data.decode())) self.transport.write(data) # close the socket self.transport.close() loop = asyncio.get_event_loop() coro = loop.create_server(EchoServer, '127.0.0.1', 8888) server = loop.run_until_complete(coro) print('serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: print("exit") finally: server.close() loop.close()
  6. ? Petr Viktorin @encukou.cz @encukou [email protected] github.com/encukou Slides available under

    the Creative Commons Attribution-ShareAlike 3.0 http://creativecommons.org/licenses/by-sa/3.0/
  7. Sources & links PEP 3156 - Asynchronous IO Support Rebooted:

    the "asyncio" Module PEP 3148 - futures - execute computations asynchronously PEP 3153 (Superseded) - Asynchronous IO support http://docs.python.org/3.4/library/asyncio.html Youtube: Guido van Rossum - Tulip: Async I/O for Python 3