bottle-file-cache 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ # Files
2
+ .coverage
3
+
4
+ # Folders
5
+ dist/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ __pycache__/
9
+ .pytest_cache/
10
+ venv/
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2025-05-25
9
+
10
+ ### Added
11
+ - First version.
12
+
13
+
14
+ [1.0.0]: https://github.com/BoboTiG/bottle-file-cache/tree/v1.0.0
@@ -0,0 +1,8 @@
1
+ MIT License
2
+ Copyright (c) 2025, Mickaël 'Tiger-222' Schoentgen
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: bottle-file-cache
3
+ Version: 1.0.0
4
+ Summary: A simple file cache for the Python Bottle web framework.
5
+ Project-URL: Homepage, https://pypi.org/project/bottle-file-cache
6
+ Project-URL: Changelog, https://github.com/BoboTiG/bottle-file-cache/blob/main/CHANGELOG.md
7
+ Project-URL: Source, https://github.com/BoboTiG/bottle-file-cache
8
+ Project-URL: Sponsor, https://github.com/sponsors/BoboTiG
9
+ Project-URL: Tracker, https://github.com/BoboTiG/bottle-file-cache/issues
10
+ Project-URL: Released Versions, https://github.com/BoboTiG/bottle-file-cache/releases
11
+ Author-email: Mickaël Schoentgen <contact@tiger-222.fr>
12
+ Maintainer-email: Mickaël Schoentgen <contact@tiger-222.fr>
13
+ License: MIT License
14
+ Copyright (c) 2025, Mickaël 'Tiger-222' Schoentgen
15
+
16
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+ License-File: LICENSE
22
+ Keywords: bottle,cache,file
23
+ Classifier: Development Status :: 5 - Production/Stable
24
+ Classifier: Environment :: Console
25
+ Classifier: Intended Audience :: Developers
26
+ Classifier: License :: OSI Approved :: MIT License
27
+ Classifier: Programming Language :: Python
28
+ Classifier: Programming Language :: Python :: 3
29
+ Classifier: Programming Language :: Python :: 3 :: Only
30
+ Classifier: Programming Language :: Python :: 3.10
31
+ Classifier: Programming Language :: Python :: 3.11
32
+ Classifier: Programming Language :: Python :: 3.12
33
+ Classifier: Programming Language :: Python :: 3.13
34
+ Classifier: Programming Language :: Python :: 3.14
35
+ Classifier: Programming Language :: Python :: Implementation :: CPython
36
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
37
+ Requires-Python: >=3.10
38
+ Provides-Extra: dev
39
+ Requires-Dist: build==1.2.2.post1; extra == 'dev'
40
+ Requires-Dist: twine==6.1.0; extra == 'dev'
41
+ Provides-Extra: tests
42
+ Requires-Dist: bottle==0.13.3; extra == 'tests'
43
+ Requires-Dist: mypy==1.15.0; extra == 'tests'
44
+ Requires-Dist: pytest-cov==6.1.1; extra == 'tests'
45
+ Requires-Dist: pytest==8.3.5; extra == 'tests'
46
+ Requires-Dist: ruff==0.11.11; extra == 'tests'
47
+ Requires-Dist: webtest==3.0.4; extra == 'tests'
48
+ Description-Content-Type: text/markdown
49
+
50
+ # Bottle File Cache
51
+
52
+ A simple file cache for the Python [Bottle](https://pypi.org/project/bottle) web framework.
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ python -m pip install -U bottle-file-cache
58
+ ```
59
+
60
+ ## Usage
61
+
62
+ Given that example:
63
+
64
+ ```python
65
+ import bottle
66
+
67
+
68
+ @bottle.route("/hello/<name>")
69
+ def index(name: str) -> str:
70
+ return bottle.template("<b>Hello {{name}}</b>!", name=name)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ bottle.run(host="localhost", port=8080)
75
+ ```
76
+
77
+ Add those lines to enable the cache:
78
+
79
+ ```diff
80
+ +from bottle_file_cache import cache
81
+ import bottle
82
+
83
+
84
+ @bottle.route("/hello/<name>")
85
+ +@cache()
86
+ def index(name: str) -> str:
87
+ return bottle.template("<b>Hello {{name}}</b>!", name=name)
88
+ ```
89
+
90
+ And that's it!
91
+
92
+ ## Advanced Usage
93
+
94
+ TODO.
@@ -0,0 +1,45 @@
1
+ # Bottle File Cache
2
+
3
+ A simple file cache for the Python [Bottle](https://pypi.org/project/bottle) web framework.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ python -m pip install -U bottle-file-cache
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Given that example:
14
+
15
+ ```python
16
+ import bottle
17
+
18
+
19
+ @bottle.route("/hello/<name>")
20
+ def index(name: str) -> str:
21
+ return bottle.template("<b>Hello {{name}}</b>!", name=name)
22
+
23
+
24
+ if __name__ == "__main__":
25
+ bottle.run(host="localhost", port=8080)
26
+ ```
27
+
28
+ Add those lines to enable the cache:
29
+
30
+ ```diff
31
+ +from bottle_file_cache import cache
32
+ import bottle
33
+
34
+
35
+ @bottle.route("/hello/<name>")
36
+ +@cache()
37
+ def index(name: str) -> str:
38
+ return bottle.template("<b>Hello {{name}}</b>!", name=name)
39
+ ```
40
+
41
+ And that's it!
42
+
43
+ ## Advanced Usage
44
+
45
+ TODO.
@@ -0,0 +1,142 @@
1
+ """Simple file cache for the Python Bottle web framework.
2
+
3
+ You can always get the latest version at:
4
+ https://github.com/BoboTiG/bottle-file-cache
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import atexit
10
+ from contextlib import suppress
11
+ from functools import wraps
12
+ from hashlib import md5
13
+ from pathlib import Path
14
+ from tempfile import TemporaryDirectory
15
+ from time import time
16
+ from types import SimpleNamespace
17
+ from typing import TYPE_CHECKING
18
+ from zlib import compress, decompress
19
+
20
+ import bottle
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable
24
+
25
+ __version__ = "1.0.0"
26
+ __author__ = "Mickaël Schoentgen"
27
+ __copyright__ = f"""
28
+ Copyright (c) 2025, {__author__}
29
+ Permission to use, copy, modify, and distribute this software and its
30
+ documentation for any purpose and without fee or royalty is hereby
31
+ granted, provided that the above copyright notice appear in all copies
32
+ and that both that copyright notice and this permission notice appear
33
+ in supporting documentation or portions thereof, including
34
+ modifications, that you make.
35
+ """
36
+
37
+ #
38
+ # Configuration
39
+ #
40
+ _TMP = TemporaryDirectory(prefix="bottle-file-", suffix="-cache", ignore_cleanup_errors=True)
41
+ atexit.register(_TMP.cleanup)
42
+
43
+ CONFIG = SimpleNamespace(
44
+ folder=Path(_TMP.name),
45
+ file_ext="cache",
46
+ expiration_in_sec=10 * 60,
47
+ append_header=True,
48
+ header_name="Cached-Since",
49
+ http_methods=["GET"],
50
+ )
51
+ ONE_MINUTE_IN_SEC = 60
52
+
53
+
54
+ #
55
+ # Utilities
56
+ #
57
+
58
+
59
+ def compute_key(text: str) -> str:
60
+ """Compute the cache key from the given `text`."""
61
+ return md5(text.encode(), usedforsecurity=False).hexdigest()
62
+
63
+
64
+ def get_file(key: str) -> Path:
65
+ """Get the cache file from the given `key`."""
66
+ return CONFIG.folder / f"{key}.{CONFIG.file_ext}"
67
+
68
+
69
+ def get_time() -> int:
70
+ """Get the Unix time."""
71
+ return int(time())
72
+
73
+
74
+ #
75
+ # CRUD
76
+ #
77
+
78
+
79
+ def create(key: str, content: str) -> str:
80
+ """Store a HTTP response into a compressed cache file."""
81
+ CONFIG.folder.mkdir(exist_ok=True, parents=True)
82
+ get_file(key).write_bytes(compress(f"{get_time()}|{content}".encode(), level=9))
83
+ return content
84
+
85
+
86
+ def read(key: str) -> str | None:
87
+ """Retreive a response from a potential cache file using the provided `key`."""
88
+ file = get_file(key)
89
+
90
+ with suppress(FileNotFoundError):
91
+ cached_at, content = decompress(file.read_bytes()).decode().split("|", 1)
92
+ elapsed = get_time() - int(cached_at)
93
+ if 0 <= elapsed < CONFIG.expiration_in_sec:
94
+ if CONFIG.append_header:
95
+ bottle.response.headers.append(CONFIG.header_name, f"{elapsed / ONE_MINUTE_IN_SEC:,.2f} min")
96
+ return content
97
+
98
+ delete(key)
99
+
100
+ return None
101
+
102
+
103
+ def delete(key: str) -> None:
104
+ """Delete a cache file."""
105
+ get_file(key).unlink(missing_ok=True)
106
+
107
+
108
+ #
109
+ # The decorator
110
+ #
111
+
112
+
113
+ def cache(**cache_kwargs: list[str]) -> Callable:
114
+ """Cache a HTTP response. Decorator to use on routes you want to cache."""
115
+
116
+ def decorator(func: Callable) -> Callable:
117
+ @wraps(func)
118
+ def wrapper(*args: str, **kwargs: str) -> str:
119
+ # No cache when:
120
+ # - Bottle runs in debug mode
121
+ # - the HTTP method is not allowed
122
+ if bottle.DEBUG or bottle.request.method not in CONFIG.http_methods:
123
+ return func(*args, **kwargs)
124
+
125
+ # The cache key is computed from the request path, first
126
+ text = bottle.request.path
127
+
128
+ # Then optional request data
129
+ for attr, values in cache_kwargs.items():
130
+ req_attr = getattr(bottle.request, attr)
131
+ for value in values:
132
+ text += f"-{req_attr.get(value, '')}"
133
+
134
+ key = compute_key(text)
135
+ return read(key) or create(key, func(*args, **kwargs))
136
+
137
+ return wrapper
138
+
139
+ return decorator
140
+
141
+
142
+ __all__ = ("cache",)
@@ -0,0 +1,142 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "bottle-file-cache"
7
+ description = "A simple file cache for the Python Bottle web framework."
8
+ readme = "README.md"
9
+ requires-python = ">= 3.10"
10
+ authors = [
11
+ { name = "Mickaël Schoentgen", email="contact@tiger-222.fr" },
12
+ ]
13
+ maintainers = [
14
+ { name = "Mickaël Schoentgen", email="contact@tiger-222.fr" },
15
+ ]
16
+ license = { file = "LICENSE" }
17
+ classifiers = [
18
+ "Development Status :: 5 - Production/Stable",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Programming Language :: Python :: Implementation :: CPython",
23
+ "Programming Language :: Python",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Programming Language :: Python :: 3.13",
30
+ "Programming Language :: Python :: 3.14",
31
+ "Topic :: Software Development :: Libraries :: Python Modules",
32
+ ]
33
+ keywords = [
34
+ "bottle",
35
+ "cache",
36
+ "file",
37
+ ]
38
+ dynamic = ["version"]
39
+
40
+ [project.urls]
41
+ Homepage = "https://pypi.org/project/bottle-file-cache"
42
+ Changelog = "https://github.com/BoboTiG/bottle-file-cache/blob/main/CHANGELOG.md"
43
+ Source = "https://github.com/BoboTiG/bottle-file-cache"
44
+ Sponsor = "https://github.com/sponsors/BoboTiG"
45
+ Tracker = "https://github.com/BoboTiG/bottle-file-cache/issues"
46
+ "Released Versions" = "https://github.com/BoboTiG/bottle-file-cache/releases"
47
+
48
+ [project.optional-dependencies]
49
+ tests = [
50
+ "bottle==0.13.3",
51
+ "mypy==1.15.0",
52
+ "pytest==8.3.5",
53
+ "pytest-cov==6.1.1",
54
+ "ruff==0.11.11",
55
+ "webtest==3.0.4",
56
+ ]
57
+ dev = [
58
+ "build==1.2.2.post1",
59
+ "twine==6.1.0",
60
+ ]
61
+
62
+ [tool.hatch.version]
63
+ path = "bottle_file_cache.py"
64
+
65
+ [tool.hatch.build.targets.sdist]
66
+ only-include = [
67
+ "CHANGELOG.md",
68
+ "bottle_file_cache.py",
69
+ ]
70
+
71
+ [tool.hatch.build.targets.wheel]
72
+ packages = [
73
+ "bottle_file_cache.py",
74
+ ]
75
+
76
+ [tool.coverage.report]
77
+ exclude_also = [
78
+ 'if TYPE_CHECKING:',
79
+ ]
80
+
81
+ [tool.mypy]
82
+ # Ensure we know what we do
83
+ warn_redundant_casts = true
84
+ warn_unused_ignores = true
85
+ warn_unused_configs = true
86
+
87
+ # Imports management
88
+ ignore_missing_imports = true
89
+ follow_imports = "skip"
90
+
91
+ # Ensure full coverage
92
+ disallow_untyped_defs = true
93
+ disallow_incomplete_defs = true
94
+ disallow_untyped_calls = true
95
+
96
+ # Restrict dynamic typing (a little)
97
+ # e.g. `x: List[Any]` or x: List`
98
+ # disallow_any_generics = true
99
+
100
+ strict_equality = true
101
+
102
+
103
+ [tool.pytest.ini_options]
104
+ addopts = """
105
+ --cov-report=term-missing:skip-covered
106
+ --cov=bottle_file_cache
107
+ --no-cov-on-fail
108
+ --showlocals
109
+ --strict-markers
110
+ -r fE
111
+ -vvv
112
+ tests/
113
+ """
114
+
115
+ [tool.ruff]
116
+ line-length = 120
117
+ indent-width = 4
118
+ target-version = "py38"
119
+
120
+ [tool.ruff.format]
121
+ quote-style = "double"
122
+ indent-style = "space"
123
+ skip-magic-trailing-comma = false
124
+ line-ending = "auto"
125
+
126
+ [tool.ruff.lint]
127
+ extend-select = ["ALL"]
128
+ ignore = [
129
+ "COM812", # conflict
130
+ "D203", # conflict
131
+ "D213", # conflict
132
+ "ISC001", # conflict
133
+ ]
134
+ fixable = ["ALL"]
135
+
136
+ [tool.ruff.lint.per-file-ignores]
137
+ "tests/*" = [
138
+ "D", # no need for documentation
139
+ "FBT003", # Boolean positional value in function call
140
+ "S101", # Use of `assert` detected
141
+ ]
142
+