Asynchronous Requests with Python requests

前端 未结 12 1396
予麋鹿
予麋鹿 2020-11-22 08:47

I tried the sample provided within the documentation of the requests library for python.

With async.map(rs), I get the response codes, but I want to get

12条回答
  •  孤城傲影
    2020-11-22 09:17

    You can use httpx for that.

    import httpx
    
    async def get_async(url):
        async with httpx.AsyncClient() as client:
            return await client.get(url)
    
    urls = ["http://google.com", "http://wikipedia.org"]
    
    # Note that you need an async context to use `await`.
    await asyncio.gather(*map(get_async, urls))
    

    if you want a functional syntax, the gamla lib wraps this into get_async.

    Then you can do

    
    await gamla.map(gamla.get_async(10))(["http://google.com", "http://wikipedia.org"])
    

    The 10 is the timeout in seconds.

    (disclaimer: I am its author)

提交回复
热议问题