python-aiohttpHow to use cache with Python Aiohttp?
Using cache with Python Aiohttp is easy and straightforward.
import aiohttp
from aiohttp_cache import Cache
cache = Cache(ttl=60)
async with aiohttp.ClientSession(cache=cache) as session:
async with session.get('http://example.com') as response:
print(await response.text())
The output of the above code will be the text content of the page http://example.com.
Code explanation
import aiohttp
: This imports the aiohttp library.from aiohttp_cache import Cache
: This imports the Cache class from the aiohttp_cache library.cache = Cache(ttl=60)
: This creates a Cache object with a time-to-live (ttl) of 60 seconds.async with aiohttp.ClientSession(cache=cache) as session
: This creates an aiohttp ClientSession object with the cache object created in the previous step.async with session.get('http://example.com') as response
: This makes a GET request to the URL http://example.com and stores the response in the response variable.print(await response.text())
: This prints the text content of the response.
Helpful links
Related
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to close a Python Aiohttp session?
- How to get response code with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to make request with basic HTTP auth using Python Aiohttp?
More of Python Aiohttp
- How to create a websocket server using Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to make request with basic HTTP auth using Python Aiohttp?
- How to close a Python Aiohttp session?
See more codes...