requests-cache / aiohttp-client-cache

An async persistent cache for aiohttp requests
MIT License
121 stars 21 forks source link

Show a warning on a cache access when a `CachedSession` context manager has been exited #290

Closed alessio-locatelli closed 3 weeks ago

alessio-locatelli commented 3 weeks ago

Closes https://github.com/requests-cache/aiohttp-client-cache/issues/241

MRE

import asyncio
from aiohttp_client_cache import CachedSession, SQLiteBackend

cache = SQLiteBackend(cache_name="./test_cache.sqlite")

async def task(n: int):
    url = f"https://httpbin.org/ip?count={n}"
    async with CachedSession(cache=cache) as session:
        return await session.get(url, ssl=False)

async def tasks(arr: list):
    tasks = [task(i) for i in arr]
    return await asyncio.gather(*tasks)

asyncio.run(tasks(list(range(10))))

1st run (there is no cache file yet)

We can see the warning inside get_connection() after the yield:

❯ python .gather_sessions.py
/usr/lib64/python3.13/contextlib.py:221: UserWarning: Cache access after closing the `Cachedsession` context manager is discouraged and can be forbidden in the future to prevent errors related to a closed database connection.
  await anext(self.gen)
Traceback (most recent call last):
[...]
sqlite3.ProgrammingError: Cannot operate on a closed database.

2nd run (a cache file already exists)

We can see the warning inside the def read():

/usr/lib64/python3.13/contextlib.py:221: UserWarning: Cache access after closing the `Cachedsession` context manager is discouraged and can be forbidden in the future to prevent errors related to a closed database connection.
  await anext(self.gen)
Traceback (most recent call last):
[...]
sqlite3.ProgrammingError: Cannot operate on a closed database.

Notes

Not related to this PR and the mentioned issue, but Redis and MongoDB must have the def close() method too because the connections must be closed.

codecov[bot] commented 3 weeks ago

Codecov Report

Attention: Patch coverage is 55.55556% with 4 lines in your changes missing coverage. Please review.

Project coverage is 96.17%. Comparing base (26bf273) to head (fb00280). Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
aiohttp_client_cache/backends/sqlite.py 50.00% 2 Missing and 2 partials :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #290 +/- ## ========================================== - Coverage 96.51% 96.17% -0.35% ========================================== Files 10 10 Lines 1063 1072 +9 Branches 186 188 +2 ========================================== + Hits 1026 1031 +5 - Misses 28 30 +2 - Partials 9 11 +2 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.