Replies: 6 comments
-
not sure what paco is, but something like this simple shows how to run concurrently, maybe worth investigating what paco.run does under the hood
|
Beta Was this translation helpful? Give feedback.
-
sorry, I should have said, paco is just a library for working with asyncio. If I use straight up asyncio like import requests
from datetime import datetime
import asyncio
URL = "http://127.0.0.1:8000/sleep/"
CALLS = 10
async def request_get():
return requests.get(URL)
async def main():
start = datetime.now()
tasks = [asyncio.create_task(request_get()) for _ in range(CALLS)]
result = await asyncio.gather(*tasks)
end = datetime.now()
print("Start time = " + start.strftime("%H:%M:%S") + "\n" +
"End time = " + end.strftime("%H:%M:%S") + "\n" +
"Elapsed = " + str(end - start) + "\n" +
"Seconds per call = " + str((end - start)/CALLS)
)
asyncio.run(main()) I get exactly the same result. In reality I have a more complex api with lots of asyncio going on inside the api. What I can't figure out is: is the api itself supposed to handle requests asynchronously? i.e. should my 10 requests be coming back in 1 second, instead of 10 seconds? I thought that they would, but maybe I'm missing something... |
Beta Was this translation helpful? Give feedback.
-
I am not sure if requests made by |
Beta Was this translation helpful? Give feedback.
-
@phy25 thanks, that has solved it. If I replace async def request_get():
return requests.get(URL) with async def request_get():
async with httpx.AsyncClient() as client:
return await client.get(URL) then it executes in one second. PHEW! I'll close the issue now. Thanks all and thanks FastAPI! |
Beta Was this translation helpful? Give feedback.
-
https://github.com/encode/requests-async might be of use as well |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here everyone! 🍰 Yep, HTTPX should be the preferred one ✔️ Thanks @tomgreenwood1 for reporting back and closing the issue 👍 |
Beta Was this translation helpful? Give feedback.
-
Description
Firstly, I just want to start by saying I love FastAPI, it's great, and thanks for all your hard work. I am just confused about whether I should expect the api to actually handle requests asynchronously or not?
If I launch a very basic api, with file: my-api.py -
and then run it with
hypercorn my-api:app
If I then hit it with 10 requests asynchronously, with a test script like
I get
So, it's handling each request sequentially... is that the intended behaviour, or have I mis-configured something?
I can work around it, but making a post route which takes a list, and then handle the list asynchronously in my code, I'm just confused about what I should be expecting here.
Additional context
Many thanks again
Beta Was this translation helpful? Give feedback.
All reactions