Skip to content

Instantly share code, notes, and snippets.

@lsbardel
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsbardel/0bc6de50835c947414b5 to your computer and use it in GitHub Desktop.
Save lsbardel/0bc6de50835c947414b5 to your computer and use it in GitHub Desktop.
asyncio server coroutine style
import asyncio
def block_read_from_database():
result = yield from asyncio.sleep(1, b'OK')
return result
class Protocol(asyncio.Protocol):
def connection_made(self, transport):
self._transport = transport
def data_received(self, data):
asyncio.async(self.response(data))
def response(self, data):
'''This is the coroutine which handle the response
'''
result = yield from block_read_from_database()
self._transport.write(result)
loop = asyncio.get_event_loop()
asyncio.async(loop.create_server(Protocol, '127.0.0.1', 3000), loop=loop)
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment