aiohttp.ClientSession
- Python course
- Advanced
- Lesson 38/83
- 5 min
Learn async HTTP with aiohttp.ClientSession.
aiohttp.ClientSession
aiohttp.ClientSession is the session class for asynchronous HTTP requests. By making many requests on the same session, you reuse connections.
import asyncio
import aiohttp
async def main():
async with aiohttp.ClientSession() as session:
async with session.get("https://example.com") as resp:
print(await resp.text())The session is opened with an async with block and closes automatically when done. Requests are made with methods like session.get and session.post.
The async with block
async with is the asynchronous context manager. It ensures the session and response open and close safely. On block exit, __aexit__ is called automatically.
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
body = await resp.text()Two nested async with blocks are used: outer for the session, inner for the response. This way the connection is released after the body is read.
Practice Async request with ClientSession
Start with import asyncio and import aiohttp. Inside async def main() open async with aiohttp.ClientSession() as session:. Inside it make the request with async with session.get("https://example.com") as resp: and print the body with print(await resp.text()). Finally add asyncio.run(main()).
Starter code
# load the asyncio and aiohttp modules
# start a session with async with (aiohttp.ClientSession)
# make a request with get on the session
# read the body with text and print it
# run main with asyncio.runSample solution
import asyncio
import aiohttp
# Define a fake session for testing
class _S:
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
def get(self, url): return self
async def text(self): return 'merhaba'
aiohttp.ClientSession = _S
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://example.com') as resp:
print(await resp.text())
asyncio.run(main())Expected output
merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ClientSession call
import aiohttp
async with ____() as session:
import aiohttp
async with aiohttp.ClientSession() as session:
Explanation: aiohttp.ClientSession() opens an async session.
2 What does async with aiohttp.ClientSession() provide?
- Caching of the response
- Automatic closing of the session Correct answer
- Making the request twice
- Changing the port number
Explanation: async with closes the session automatically on block exit.
3 Match the ClientSession concepts
| Term | Meaning |
|---|---|
ClientSession |
Opens a session |
async with |
Closes automatically |
session.get |
Makes a GET request |
await resp.text |
Returns body |