summaryrefslogtreecommitdiff
path: root/requests_cache/backends/sqlite.py
diff options
context:
space:
mode:
authorJordan Cook <jordan.cook@pioneer.com>2021-08-20 23:53:27 -0500
committerJordan Cook <jordan.cook@pioneer.com>2021-08-21 14:13:28 -0500
commitca2ed80089f9f3ec73aa4953d1ae95153229669f (patch)
tree0399d474f71f1d9b67aeb4e753c3cfa10c28adbb /requests_cache/backends/sqlite.py
parent901a2b997ecc15500c1874123a399a1464342e53 (diff)
downloadrequests-cache-ca2ed80089f9f3ec73aa4953d1ae95153229669f.tar.gz
Add appdirs as a dependency, and add 'use_cache_dir' option to SQLite and Filesystem backends
Diffstat (limited to 'requests_cache/backends/sqlite.py')
-rw-r--r--requests_cache/backends/sqlite.py54
1 files changed, 37 insertions, 17 deletions
diff --git a/requests_cache/backends/sqlite.py b/requests_cache/backends/sqlite.py
index a66e228..ed671f5 100644
--- a/requests_cache/backends/sqlite.py
+++ b/requests_cache/backends/sqlite.py
@@ -54,7 +54,7 @@ Special System Paths
If you don't know exactly where you want to put your cache file, your **system's default temp
directory** or **cache directory** is a good choice.
-Use a temp directory with the ``use_temp`` option:
+Use your system's default temp directory with the ``use_temp`` option:
>>> session = CachedSession('http_cache', use_temp=True)
>>> print(session.cache.db_path)
@@ -64,12 +64,14 @@ Use a temp directory with the ``use_temp`` option:
If the cache name is an absolute path, the ``use_temp`` option will be ignored. If it's a
relative path, it will be relative to the temp directory.
+Use your system's default cache directory with the ``use_cache_dir`` option:
+
If you want an easy cross-platform way to get the system cache directory, use the
`appdirs <https://github.com/ActiveState/appdirs>`_ library:
- >>> from appdirs import user_cache_dir
- >>> db_path = join(user_cache_dir('requests_cache'), 'http_cache')
- >>> session = CachedSession(db_path, use_temp=True)
+ >>> session = CachedSession('http_cache', use_cache_dir=True)
+ >>> print(session.cache.db_path)
+ '/home/user/.cache/http_cache.sqlite'
In-Memory Caching
~~~~~~~~~~~~~~~~~
@@ -132,6 +134,8 @@ from pathlib import Path
from tempfile import gettempdir
from typing import Collection, Iterable, Iterator, List, Tuple, Type, Union
+from appdirs import user_cache_dir
+
from . import BaseCache, BaseStorage, get_valid_kwargs
MEMORY_URI = 'file::memory:?cache=shared'
@@ -144,6 +148,7 @@ class SQLiteCache(BaseCache):
Args:
db_path: Database file path (expands user paths and creates parent dirs)
+ use_cache_dir: Store datebase in a user cache directory (e.g., `~/.cache/http_cache.sqlite`)
use_temp: Store database in a temp directory (e.g., ``/tmp/http_cache.sqlite``)
use_memory: Store database in memory instead of in a file
fast_save: Significantly increases cache write performance, but with the possibility of data
@@ -191,13 +196,16 @@ class SQLiteDict(BaseStorage):
db_path,
table_name='http_cache',
fast_save=False,
- use_temp: bool = False,
+ use_cache_dir: bool = False,
use_memory: bool = False,
+ use_temp: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.connection_kwargs = get_valid_kwargs(sqlite_template, kwargs)
- self.db_path = _get_db_path(db_path, use_temp, use_memory)
+ self.db_path = _get_sqlite_cache_path(
+ db_path, use_cache_dir=use_cache_dir, use_temp=use_temp, use_memory=use_memory
+ )
self.fast_save = fast_save
self.table_name = table_name
@@ -336,27 +344,39 @@ def _format_sequence(values: Collection) -> Tuple[str, List]:
return ','.join(['?'] * len(values)), list(values)
-def _get_db_path(db_path: Union[Path, str], use_temp: bool, use_memory: bool) -> str:
- """Get resolved path for database file"""
- db_path = str(db_path)
+def _get_sqlite_cache_path(
+ db_path: Union[Path, str], use_cache_dir: bool, use_temp: bool, use_memory: bool = False
+) -> str:
+ """Get a resolved path for a SQLite database file (or memory URI("""
# Use an in-memory database, if specified
+ db_path = str(db_path)
if use_memory:
return MEMORY_URI
elif ':memory:' in db_path or 'mode=memory' in db_path:
return db_path
- # Save to a temp directory, if specified
- if use_temp and not isabs(db_path):
- db_path = join(gettempdir(), db_path)
-
- # Expand relative and user paths (~/*), and add file extension if not specified
- db_path = abspath(expanduser(db_path))
+ # Add file extension if not specified
if '.' not in basename(db_path):
db_path += '.sqlite'
+ return get_cache_path(db_path, use_cache_dir, use_temp)
+
+
+def get_cache_path(
+ db_path: Union[Path, str], use_cache_dir: bool = False, use_temp: bool = False
+) -> str:
+ """Get a resolved cache path"""
+ db_path = str(db_path)
+
+ # Save to platform-specific temp or user cache directory, if specified
+ if use_cache_dir and not isabs(db_path):
+ db_path = join(user_cache_dir(), db_path)
+ elif use_temp and not isabs(db_path):
+ db_path = join(gettempdir(), db_path)
- # Make sure parent dirs exist
+ # Expand relative and user paths (~/*), and make sure parent dirs exist
+ db_path = abspath(expanduser(db_path))
makedirs(dirname(db_path), exist_ok=True)
- return db_path
+ return str(db_path)
def sqlite_template(