-1

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())
6
  • Use an asynchronous HTTP library like docs.aiohttp.org/en ! Commented Mar 9, 2022 at 15:00
  • 2
    @KlausD. This page does not exist yet. Commented Mar 9, 2022 at 15:02
  • If you don't want loop to wait for each task, don't await each task! gather them once you have created all of them. Commented Mar 9, 2022 at 15:09
  • Does this answer your question? Why does await asyncio.create_task() behave different then when assigning it to a variable? Commented Mar 9, 2022 at 15:13
  • Note that requests is a synchronous library. Don't use it in an asynchronous event loop, since it will block the entire loop – and thus all its tasks – while working. Commented Mar 9, 2022 at 15:14

1 Answer 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]
    
Sign up to request clarification or add additional context in comments.

1 Comment

That's right- this is exactly what I need. just async version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.