summaryrefslogtreecommitdiff
path: root/requests_cache
diff options
context:
space:
mode:
authorJordan Cook <JWCook@users.noreply.github.com>2021-08-21 14:14:27 -0500
committerGitHub <noreply@github.com>2021-08-21 14:14:27 -0500
commit8985753310d099489ad7a5a0f33253ccaed11d9b (patch)
treee6d47f9f5bd8424264a38d85a03df2cc77f6beb8 /requests_cache
parent901a2b997ecc15500c1874123a399a1464342e53 (diff)
parent86a62d4998866df2b9a0226895a9cb6b517078d9 (diff)
downloadrequests-cache-8985753310d099489ad7a5a0f33253ccaed11d9b.tar.gz
Merge pull request #369 from JWCook/appdirs
Add option to use user cache dir (~/.cache, etc.) for SQLite and Filesystem backends
Diffstat (limited to 'requests_cache')
-rw-r--r--requests_cache/backends/filesystem.py28
-rw-r--r--requests_cache/backends/sqlite.py54
2 files changed, 49 insertions, 33 deletions
diff --git a/requests_cache/backends/filesystem.py b/requests_cache/backends/filesystem.py
index 63d83ba..a70a6f7 100644
--- a/requests_cache/backends/filesystem.py
+++ b/requests_cache/backends/filesystem.py
@@ -38,16 +38,15 @@ API Reference
from contextlib import contextmanager
from glob import glob
from os import listdir, makedirs, unlink
-from os.path import abspath, basename, dirname, expanduser, isabs, join, splitext
+from os.path import basename, dirname, join, splitext
from pathlib import Path
from pickle import PickleError
from shutil import rmtree
-from tempfile import gettempdir
from typing import List, Union
from ..serializers import SERIALIZERS
from . import BaseCache, BaseStorage
-from .sqlite import SQLiteDict
+from .sqlite import SQLiteDict, get_cache_path
class FileCache(BaseCache):
@@ -55,6 +54,7 @@ class FileCache(BaseCache):
Args:
cache_name: Base directory for cache files
+ use_cache_dir: Store datebase in a user cache directory (e.g., `~/.cache/`)
use_temp: Store cache files in a temp directory (e.g., ``/tmp/http_cache/``).
Note: if ``cache_name`` is an absolute path, this option will be ignored.
extension: Extension for cache files. If not specified, the serializer default extension
@@ -75,9 +75,16 @@ class FileCache(BaseCache):
class FileDict(BaseStorage):
"""A dictionary-like interface to files on the local filesystem"""
- def __init__(self, cache_name, use_temp: bool = False, extension: str = None, **kwargs):
+ def __init__(
+ self,
+ cache_name,
+ use_temp: bool = False,
+ use_cache_dir: bool = False,
+ extension: str = None,
+ **kwargs,
+ ):
super().__init__(**kwargs)
- self.cache_dir = _get_cache_dir(cache_name, use_temp)
+ self.cache_dir = get_cache_path(cache_name, use_cache_dir=use_cache_dir, use_temp=use_temp)
self.extension = extension if extension is not None else _get_default_ext(self.serializer)
self.is_binary = False
makedirs(self.cache_dir, exist_ok=True)
@@ -135,17 +142,6 @@ class FileDict(BaseStorage):
return glob(self._path('*'))
-def _get_cache_dir(cache_dir: Union[Path, str], use_temp: bool) -> str:
- # Save to a temp directory, if specified
- if use_temp and not isabs(cache_dir):
- cache_dir = join(gettempdir(), cache_dir, 'responses')
-
- # Expand relative and user paths (~/*), and make sure parent dirs exist
- cache_dir = abspath(expanduser(str(cache_dir)))
- makedirs(cache_dir, exist_ok=True)
- return cache_dir
-
-
def _get_default_ext(serializer) -> str:
for k, v in SERIALIZERS.items():
if serializer is v:
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(