Skip to content

Instantly share code, notes, and snippets.

@travishen
Last active May 10, 2022 12:29
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 travishen/231e82ecbd85802decfa5f4fff7893f3 to your computer and use it in GitHub Desktop.
Save travishen/231e82ecbd85802decfa5f4fff7893f3 to your computer and use it in GitHub Desktop.
@asyncio.coroutine
def init(loop, address, port):
"""Yield a server for event loop to drive"""
app = aiohttp.web.Application(loop=loop)
# you should consider make `home` a corutine to prevent blocking
app.router.add_route('GET', '/', home)
handler = app.make_handler()
# create_server brings up the server, using handler as the protocol handler and binding it to address and port
server = yield from loop.create_server(handler, address, port)
retrun server.sockets[0].getsockname()
def main(address='127.0.0.1', port=8888):
port = int(port)
loop = asyncio.get_event_loop()
host = loop.run_until_complete(init(loop, address, port))
print(f'Serving on {host}. Hit CTRL-C to stop')
try:
loop.run_forever()
except KeyboardInterrupt:
pass
print('Server shutting down.')
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment