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 get response code with Python Aiohttp?
- How to create a websocket server using 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 get request parameters using Python Aiohttp?
- How to get JSON data using Python Aiohttp?
- How to download large files with Python Aiohttp?
- How to download a file with Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
More of Python Aiohttp
- How to use keepalive with Python Aiohttp?
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to set query parameters with Python Aiohttp?
- How to make parallel requests with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to get JSON data using Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
See more codes...