python-aiohttpHow to make parallel requests with Python Aiohttp?
Parallel requests with Python Aiohttp can be made using the asyncio
library. The following example code shows how to make two requests in parallel:
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html1 = await fetch(session, 'http://example.com/1')
html2 = await fetch(session, 'http://example.com/2')
print(html1)
print(html2)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Output example
<html>
<head>
<title>Example 1</title>
</head>
<body>
<h1>Example 1</h1>
</body>
</html>
<html>
<head>
<title>Example 2</title>
</head>
<body>
<h1>Example 2</h1>
</body>
</html>
The code consists of the following parts:
import asyncio
andimport aiohttp
: imports theasyncio
andaiohttp
libraries.async def fetch(session, url)
: defines an asynchronous function that takes a session and a URL as parameters and returns the response text.async def main()
: defines an asynchronous function that makes two requests in parallel using thefetch
function.loop = asyncio.get_event_loop()
: creates an event loop.loop.run_until_complete(main())
: runs themain
function until it is complete.
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to get response code with Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to use Python Aiohttp and FastAPI?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to close a Python Aiohttp session?
- Bearer token request example with Python Aiohttp?
- How to rate limit with Python Aiohttp?
See more codes...