Python nonblocking server

Viewed 1336

I try to write simple nonblocking http server. I can't manage to all routines (Task1, Task2 and server) run simultaneous. Whatewer I do the server block.

import asyncio
from aiohttp import web


async def Task1():
    for i in range(100):
        print ('Task-1',i)
        await asyncio.sleep(1)


async def Task2():
    for i in range(100):
        print ('Task-2',i)
        await asyncio.sleep(2)

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)



app = web.Application()
app.add_routes([web.get('/', handle), web.get('/{name}', handle)])


loop=asyncio.new_event_loop()
loop.create_task(Task1())
loop.create_task(Task2())
loop.create_task(web.run_app(app)) #with this line commented task1/2 works
loop.run_forever()

The expected result should be printed on terminal while server runs. But I got terminal output OR server running (commenting second line from end) but want both.

Task-1 0
Task-2 0
Task-1 1
Task-2 1
Task-1 2
Task-1 3
Task-2 2
Task-1 4
Task-1 5
Task-2 3
Task-1 6
---more--- 
3 Answers

run_app is a convenience function that sets up the server and runs the event loop until the server shuts down. It is a synchronous function meant for simple examples, and as such not meant to be passed to create_task. The only reason create_task doesn't raise an exception is because run_app never returns, so the final create_task doesn't actually get called.

To obtain control over the event loop and add other tasks to it, you can start your server using the AppRunner. For example (untested):

async def main():
    # create the application, as before
    app = aiohttp.web.Application()
    app.add_routes([
        aiohttp.web.get('/', handle),
        aiohttp.web.get('/{name}', handle)
    ])

    # add some tasks into the current event loop
    asyncio.create_task(Task1())
    asyncio.create_task(Task2())

    # set up the web server
    runner = aiohttp.web.AppRunner(app)
    await runner.setup()
    await aiohttp.web.TCPSite(runner).start()

    # wait forever, running both the web server and the tasks
    await asyncio.Event().wait()

asyncio.run(main())

I need to do little modification and got it working...

import asyncio
from aiohttp import web


async def Task1():
    for i in range(100):
        print ('Task-1',i)
        await asyncio.sleep(1)


async def Task2():
    for i in range(100):
        print ('Task-2',i)
        await asyncio.sleep(2)



async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

async def HttspServer():
    # create the application, as before
    app = web.Application()
    app.add_routes([
        web.get('/', handle),
        web.get('/{name}', handle)
    ])

    # set up the web server
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner)
    await site.start()

    # wait forever, running both the web server and the tasks
    await asyncio.Event().wait()


loop=asyncio.new_event_loop()
loop.create_task(Task1())
loop.create_task(Task2())
loop.create_task(HttspServer())
loop.run_forever()

So this should be final solution?

#!/usr/bin/python
# -*- coding: utf8 -*-
import asyncio
from aiohttp import web


async def Task1():
    for i in range(100):
        print ('Task-1',i)
        await asyncio.sleep(1)

async def Task2():
    for i in range(100):
        print ('Task-2',i)
        await asyncio.sleep(2)

async def handle(request):
    data = {'some': 'data'}
    return web.json_response(data)

async def main():
    # create the application, as before
    app = web.Application()
    app.add_routes([
        web.get('/', handle),
        web.get('/{name}', handle)
    ])

    # add some tasks into the current event loop
    loop = asyncio.get_event_loop()
    loop.create_task(Task1())
    loop.create_task(Task2())

    # set up the web server
    runner = web.AppRunner(app)
    await runner.setup()
    await web.TCPSite(runner).start()

    # wait forever, running both the web server and the tasks
    await asyncio.Event().wait()

asyncio.get_event_loop().run_until_complete(main())
Related