How can I send an HTTP request from my FastAPI app to another site?

后端 未结 2 1563
攒了一身酷
攒了一身酷 2020-12-18 04:09

I am trying to send 100 requests at a time to a server http://httpbin.org/uuid using the following code snippet

from fastapi import FastAPI
         


        
2条回答
  •  孤城傲影
    2020-12-18 04:51

    requests is a synchronous library. You need to use an asyncio-based library to make hundreds of requests asynchronously.

    aiohttp example

    from fastapi import FastAPI
    from time import time
    import aiohttp
    import asyncio
    
    app = FastAPI()
    
    URL = "http://httpbin.org/uuid"
    
    
    async def main(session):
        async with session.get(URL) as response:
            return await response.text()
    
    
    async def task():
        async with aiohttp.ClientSession() as session:
            tasks = [main(session) for i in range(100)]
            result = await asyncio.gather(*tasks)
            print(result)
    
    
    @app.get('/')
    async def f():
        start = time()
        await task()
        print("time: ", time() - start)
    

    Output

    ['{\n  "uuid": "65c454bf-9b12-4ba8-98e1-de636bffeed3"\n}\n', '{\n  "uuid": "03a48e56-2a44-48e3-bd43-a0b605bef359"\n}\n',...
    time:  0.5911855697631836
    

    httpx example

    import uvicorn
    from fastapi import FastAPI
    from time import time
    import httpx
    import asyncio
    
    app = FastAPI()
    
    URL = "http://httpbin.org/uuid"
    
    
    async def main(client):
        response = await client.get(URL)
        return response.text
    
    
    async def task():
        async with httpx.AsyncClient() as client:
            tasks = [main(client) for i in range(100)]
            result = await asyncio.gather(*tasks)
            print(result)
    
    
    @app.get('/')
    async def f():
        start = time()
        await task()
        print("time: ", time() - start)
    

提交回复
热议问题