diff options
| author | Jordan Cook <jordan.cook@pioneer.com> | 2022-04-22 17:29:38 -0500 |
|---|---|---|
| committer | Jordan Cook <jordan.cook@pioneer.com> | 2022-04-22 17:57:22 -0500 |
| commit | 4e1697f5fc6065fd6bc6b60f5f3b5f3ab8a98527 (patch) | |
| tree | c62e6a01635ac65d36464579fb248a25cc49b2c1 /requests_cache | |
| parent | 1a4468abb249ec3ea2c1a774bd14fded14e28d69 (diff) | |
| download | requests-cache-4e1697f5fc6065fd6bc6b60f5f3b5f3ab8a98527.tar.gz | |
Add SQLiteDict.size() method to estimate the database size
Diffstat (limited to 'requests_cache')
| -rw-r--r-- | requests_cache/backends/sqlite.py | 18 |
1 files changed, 17 insertions, 1 deletions
diff --git a/requests_cache/backends/sqlite.py b/requests_cache/backends/sqlite.py index 74e0d71..3652481 100644 --- a/requests_cache/backends/sqlite.py +++ b/requests_cache/backends/sqlite.py @@ -9,7 +9,7 @@ import threading from contextlib import contextmanager from logging import getLogger from os import unlink -from os.path import isfile +from os.path import getsize, isfile from pathlib import Path from tempfile import gettempdir from time import time @@ -266,6 +266,22 @@ class SQLiteDict(BaseStorage): con.execute(f"DELETE FROM {self.table_name} WHERE expires <= ?", (round(time()),)) self.vacuum() + def size(self) -> int: + """Return the size of the database, in bytes. For an in-memory database, this will be an + estimate based on page size. + """ + try: + return getsize(self.db_path) + except IOError: + return self._estimate_size() + + def _estimate_size(self) -> int: + """Estimate the current size of the database based on page count * size""" + with self.connection() as conn: + page_count = conn.execute('PRAGMA page_count').fetchone()[0] + page_size = conn.execute('PRAGMA page_size').fetchone()[0] + return page_count * page_size + def sorted( self, key: str = 'expires', reversed: bool = False, limit: int = None, exclude_expired=False ): |
