'function in function async loop

I'm going to call the unspecified number of the counter function from inside the loop function And the counter function also call the send_request function

just i want counter do not wait for the send_request answer , when HTTP response Arrived print

import requests
import asyncio
import random 


async def counter(i):
    print("Started counter ",i)
    await asyncio.create_task(send_request(random.randint(1,10)))
                                   
async def send_request(i):
    print("Sending HTTP request  ",i)
    await asyncio.sleep(i)
    r = requests.get('http://example.com')
    print(f"Got HTTP response with status {r.status_code} in time {i}")

@app.incomeing_msg(i)
async def loop(i):
    asyncio.create_task(counter(i))
        
asyncio.run(loop())


Solution 1:[1]

BTW if you want to send n requests in parallel you can use threading and write something like this:

from threading import Thread
import requests
import random
import time


def counter(i):
    print("Started counter ", i)
    send_request(random.randint(1, 10))


def send_request(i):
    print("Sending HTTP request  ", i)
    time.sleep(i)
    r = requests.get('http://example.com')
    print(f"Got HTTP response with status {r.status_code} in time {i}")


def loop():
    n = 5 
    tasks = [Thread(target=counter, args=(i, )) for i in range(n)]
    [t.start() for t in tasks]
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Rn