0

I'm having a small web server that that i'm trying to run async functions on web request:

from aiohttp import web
import asyncio

    async def funcB():
        while True:
              print("running")
    
    async def funcA(req):
        print('start')
        asyncio.Task(funcB())
        print('execute task completed')
        return web.Response(text="OK Start");
    
    
    if __name__ == '__main__':
    
        app = web.Application()
        app.add_routes([web.get('/', funcA)])
        web.run_app(app, host='127.0.0.1', port=2000)

Once running the app and triggering it by curl http://127.0.0.1:2000/ i do get the execute task completed logline, but the curl response of the curl is not been received, if I comment out the asyncio.Task(funcB()) line - I do get the response of the CURL command - I must say that funcB dose run..

what do I miss here?

USer22999299
  • 5,284
  • 9
  • 46
  • 78
  • I am getting curl response in both cases. also, funcB keeps running in your case because of infinite while loop. – SajanGohil May 06 '22 at 10:57
  • @SajanGohil But that's the case, I'm looking for a way to run an infinite loop in different task / thread .. – USer22999299 May 06 '22 at 13:02
  • ok, but I can't reproduce your original issue of not getting a curl response – SajanGohil May 06 '22 at 13:03
  • `asyncio.Task(funcB())` doesn’t actually run your task, it just creates a `Task` object. That’s why your problem can’t be reproduced. That said, your actual problem is that `funcB` never yields back to the event loop. Either it needs to await something they does, or you should use a separate thread or process, depending on whether it’s I/O or CPU bound. – dirn May 06 '22 at 14:45
  • @dirn hmm... i was under the assumption that this create a new thread - i saw it return a future - if thats not the case how shell i spin funcB in a separated thread? – USer22999299 May 06 '22 at 15:49
  • Found answer here: https://stackoverflow.com/questions/59645272/how-do-i-pass-an-async-function-to-a-thread-target-in-python – USer22999299 May 06 '22 at 17:17

0 Answers0