Search code examples
pythonpython-3.xaiohttp

app = web.Application(loop=loop) in aiohttp docs


I have a problem with loop=loop when I was reading the aiohttp docs. Is it a special and indispensable code? Or just a redundant reassignment that app = web.Application(loop) works as well.

Server example:

import asyncio
from aiohttp import web

@asyncio.coroutine
def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(body=text.encode('utf-8'))


@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)  #Why use loop=loop?
    app.router.add_route('GET', '/{name}', handle)

    srv = yield from loop.create_server(app.make_handler(),
                                        '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

Solution

  • loop parameter from web.Application constructor is keyword-only (see PEP 3102 for details). So you should use name=value notation for it.