everynow 0.4.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.
- everynow-0.4.0/CHANGELOG.md +41 -0
- everynow-0.4.0/LICENSE +21 -0
- everynow-0.4.0/MANIFEST.in +5 -0
- everynow-0.4.0/PKG-INFO +164 -0
- everynow-0.4.0/README.md +119 -0
- everynow-0.4.0/everynow/__init__.py +50 -0
- everynow-0.4.0/everynow/cache.py +152 -0
- everynow-0.4.0/everynow/config.py +175 -0
- everynow-0.4.0/everynow/files.py +108 -0
- everynow-0.4.0/everynow/http.py +158 -0
- everynow-0.4.0/everynow/log.py +104 -0
- everynow-0.4.0/everynow/py.typed +0 -0
- everynow-0.4.0/everynow/rate.py +97 -0
- everynow-0.4.0/everynow/retry.py +145 -0
- everynow-0.4.0/everynow/terminal.py +261 -0
- everynow-0.4.0/everynow/timing.py +87 -0
- everynow-0.4.0/everynow/validate.py +81 -0
- everynow-0.4.0/everynow.egg-info/PKG-INFO +164 -0
- everynow-0.4.0/everynow.egg-info/SOURCES.txt +23 -0
- everynow-0.4.0/everynow.egg-info/dependency_links.txt +1 -0
- everynow-0.4.0/everynow.egg-info/requires.txt +21 -0
- everynow-0.4.0/everynow.egg-info/top_level.txt +1 -0
- everynow-0.4.0/pyproject.toml +74 -0
- everynow-0.4.0/setup.cfg +4 -0
- everynow-0.4.0/tests/test_basic.py +76 -0
|
@@ -0,0 +1,41 @@
|
|
|
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.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.4.0] - 2026-11-28
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- Async HTTP client (`aget`, `apost`, `arequest`)
|
|
12
|
+
- Rate limiting (`RateLimiter`, `rate_limit` decorator)
|
|
13
|
+
- Timing utilities (`Timer`, `timer`, `timed`, `benchmark`)
|
|
14
|
+
- Expanded validation helpers (`is_phone`, `length`, `matches`, `ensure`)
|
|
15
|
+
- Improved logging (JSON mode + file output)
|
|
16
|
+
- Full type hints and `py.typed` marker
|
|
17
|
+
- Basic test suite
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
- Bumped minimum Python version to 3.10
|
|
21
|
+
- Improved public API surface and documentation
|
|
22
|
+
|
|
23
|
+
## [0.3.0] - 2026-11-28
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
- Async retry (`aretry`) and async cache (`acache`)
|
|
27
|
+
- Lightweight HTTP client with built-in retry
|
|
28
|
+
- Validation module
|
|
29
|
+
- Significant rewrite of core modules
|
|
30
|
+
|
|
31
|
+
## [0.2.0] - 2026-11-27
|
|
32
|
+
|
|
33
|
+
### Added
|
|
34
|
+
- Logging helpers
|
|
35
|
+
- Better terminal, cache, files and config modules
|
|
36
|
+
- Improved packaging
|
|
37
|
+
|
|
38
|
+
## [0.1.0] - 2026-11-27
|
|
39
|
+
|
|
40
|
+
### Added
|
|
41
|
+
- Initial release with config, retry, terminal, cache and files utilities
|
everynow-0.4.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vikas Patel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
everynow-0.4.0/PKG-INFO
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: everynow
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Modern everyday Python utilities — config, retry (sync+async), terminal, cache, HTTP, rate limiting, timing, validation, logging & files. Lightweight and zero hard dependencies.
|
|
5
|
+
Author: Vikas Patel
|
|
6
|
+
Maintainer: Vikas Patel
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/VikasPatel22/everynow
|
|
9
|
+
Project-URL: Documentation, https://github.com/VikasPatel22/everynow#readme
|
|
10
|
+
Project-URL: Repository, https://github.com/VikasPatel22/everynow
|
|
11
|
+
Project-URL: Issues, https://github.com/VikasPatel22/everynow/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/VikasPatel22/everynow/blob/main/CHANGELOG.md
|
|
13
|
+
Keywords: utils,utilities,config,retry,async,cache,http,terminal,cli,rate-limit,timing,logging,validation,toolkit,helpers,productivity
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Topic :: Utilities
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Classifier: Framework :: AsyncIO
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Provides-Extra: yaml
|
|
32
|
+
Requires-Dist: pyyaml>=6.0; extra == "yaml"
|
|
33
|
+
Provides-Extra: toml
|
|
34
|
+
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "toml"
|
|
35
|
+
Provides-Extra: all
|
|
36
|
+
Requires-Dist: pyyaml>=6.0; extra == "all"
|
|
37
|
+
Requires-Dist: tomli>=2.0; python_version < "3.11" and extra == "all"
|
|
38
|
+
Provides-Extra: dev
|
|
39
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
40
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
41
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
42
|
+
Requires-Dist: build; extra == "dev"
|
|
43
|
+
Requires-Dist: twine; extra == "dev"
|
|
44
|
+
Dynamic: license-file
|
|
45
|
+
|
|
46
|
+
# everynow
|
|
47
|
+
|
|
48
|
+
**Modern everyday Python utilities**
|
|
49
|
+
|
|
50
|
+
[](https://pypi.org/project/everynow/)
|
|
51
|
+
[](https://pypi.org/project/everynow/)
|
|
52
|
+
[](https://opensource.org/licenses/MIT)
|
|
53
|
+
|
|
54
|
+
Lightweight • Fully typed • Async capable • **Zero hard dependencies**
|
|
55
|
+
|
|
56
|
+
Built for real CLI tools, automation, Termux, scripts, APIs, and small services.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Features
|
|
61
|
+
|
|
62
|
+
| Module | Capabilities |
|
|
63
|
+
|--------|--------------|
|
|
64
|
+
| **config** | `.env` + YAML/TOML/JSON, deep merge, nested env overrides |
|
|
65
|
+
| **retry** | Sync + **Async** retry (exponential backoff + jitter) |
|
|
66
|
+
| **terminal** | Spinner, progress bar, colors, tables, prompts |
|
|
67
|
+
| **cache** | TTL cache + **async cache** + disk persistence |
|
|
68
|
+
| **http** | Sync + **Async** HTTP client with built-in retry (stdlib only) |
|
|
69
|
+
| **rate** | Token-bucket rate limiter (sync + async + decorator) |
|
|
70
|
+
| **timing** | Timer, context manager, decorator, benchmark |
|
|
71
|
+
| **files** | Atomic writes, hashing, find, JSON helpers, temp dirs |
|
|
72
|
+
| **log** | Colored console + optional JSON + file logging |
|
|
73
|
+
| **validate** | Email, URL, phone, length, one_of, between, require... |
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Installation
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install everynow
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Optional extras:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install everynow[yaml] # YAML config support
|
|
87
|
+
pip install everynow[all] # YAML + TOML helpers
|
|
88
|
+
pip install everynow[dev] # development tools
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## Quick Start
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from everynow import (
|
|
97
|
+
spinner, progress, success, info,
|
|
98
|
+
retry, aretry, cache, acache,
|
|
99
|
+
get, aget, rate_limit, timer, timed,
|
|
100
|
+
load_config, get_logger, require, is_email
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Terminal
|
|
104
|
+
with spinner("Working..."):
|
|
105
|
+
...
|
|
106
|
+
|
|
107
|
+
with progress(100, prefix="Processing") as p:
|
|
108
|
+
for _ in range(100):
|
|
109
|
+
p.update()
|
|
110
|
+
|
|
111
|
+
# Retry (sync + async)
|
|
112
|
+
@retry(tries=5, delay=0.4)
|
|
113
|
+
def fetch():
|
|
114
|
+
...
|
|
115
|
+
|
|
116
|
+
@aretry(tries=5)
|
|
117
|
+
async def afetch():
|
|
118
|
+
...
|
|
119
|
+
|
|
120
|
+
# HTTP with automatic retry
|
|
121
|
+
resp = get("https://httpbin.org/get")
|
|
122
|
+
print(resp.status, resp.json())
|
|
123
|
+
|
|
124
|
+
# Rate limiting
|
|
125
|
+
@rate_limit(rate=2, per=1) # max 2 calls per second
|
|
126
|
+
def call_api():
|
|
127
|
+
...
|
|
128
|
+
|
|
129
|
+
# Timing
|
|
130
|
+
with timer("process"):
|
|
131
|
+
heavy_work()
|
|
132
|
+
|
|
133
|
+
# Config + Validation
|
|
134
|
+
cfg = load_config(".env", env_prefix="APP_")
|
|
135
|
+
email = is_email(cfg.get("user_email", ""))
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
## Design Philosophy
|
|
141
|
+
|
|
142
|
+
- **Zero hard dependencies** — works out of the box
|
|
143
|
+
- **First-class async** support
|
|
144
|
+
- **Excellent developer experience**
|
|
145
|
+
- **Fully typed** (ships with `py.typed`)
|
|
146
|
+
- **CLI & automation focused**
|
|
147
|
+
- **Small and readable** source
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Development
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
git clone https://github.com/VikasPatel22/everynow.git
|
|
155
|
+
cd everynow
|
|
156
|
+
pip install -e ".[dev]"
|
|
157
|
+
pytest
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## License
|
|
163
|
+
|
|
164
|
+
MIT © Vikas Patel
|
everynow-0.4.0/README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# everynow
|
|
2
|
+
|
|
3
|
+
**Modern everyday Python utilities**
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/everynow/)
|
|
6
|
+
[](https://pypi.org/project/everynow/)
|
|
7
|
+
[](https://opensource.org/licenses/MIT)
|
|
8
|
+
|
|
9
|
+
Lightweight • Fully typed • Async capable • **Zero hard dependencies**
|
|
10
|
+
|
|
11
|
+
Built for real CLI tools, automation, Termux, scripts, APIs, and small services.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
| Module | Capabilities |
|
|
18
|
+
|--------|--------------|
|
|
19
|
+
| **config** | `.env` + YAML/TOML/JSON, deep merge, nested env overrides |
|
|
20
|
+
| **retry** | Sync + **Async** retry (exponential backoff + jitter) |
|
|
21
|
+
| **terminal** | Spinner, progress bar, colors, tables, prompts |
|
|
22
|
+
| **cache** | TTL cache + **async cache** + disk persistence |
|
|
23
|
+
| **http** | Sync + **Async** HTTP client with built-in retry (stdlib only) |
|
|
24
|
+
| **rate** | Token-bucket rate limiter (sync + async + decorator) |
|
|
25
|
+
| **timing** | Timer, context manager, decorator, benchmark |
|
|
26
|
+
| **files** | Atomic writes, hashing, find, JSON helpers, temp dirs |
|
|
27
|
+
| **log** | Colored console + optional JSON + file logging |
|
|
28
|
+
| **validate** | Email, URL, phone, length, one_of, between, require... |
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install everynow
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Optional extras:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install everynow[yaml] # YAML config support
|
|
42
|
+
pip install everynow[all] # YAML + TOML helpers
|
|
43
|
+
pip install everynow[dev] # development tools
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Quick Start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from everynow import (
|
|
52
|
+
spinner, progress, success, info,
|
|
53
|
+
retry, aretry, cache, acache,
|
|
54
|
+
get, aget, rate_limit, timer, timed,
|
|
55
|
+
load_config, get_logger, require, is_email
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# Terminal
|
|
59
|
+
with spinner("Working..."):
|
|
60
|
+
...
|
|
61
|
+
|
|
62
|
+
with progress(100, prefix="Processing") as p:
|
|
63
|
+
for _ in range(100):
|
|
64
|
+
p.update()
|
|
65
|
+
|
|
66
|
+
# Retry (sync + async)
|
|
67
|
+
@retry(tries=5, delay=0.4)
|
|
68
|
+
def fetch():
|
|
69
|
+
...
|
|
70
|
+
|
|
71
|
+
@aretry(tries=5)
|
|
72
|
+
async def afetch():
|
|
73
|
+
...
|
|
74
|
+
|
|
75
|
+
# HTTP with automatic retry
|
|
76
|
+
resp = get("https://httpbin.org/get")
|
|
77
|
+
print(resp.status, resp.json())
|
|
78
|
+
|
|
79
|
+
# Rate limiting
|
|
80
|
+
@rate_limit(rate=2, per=1) # max 2 calls per second
|
|
81
|
+
def call_api():
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
# Timing
|
|
85
|
+
with timer("process"):
|
|
86
|
+
heavy_work()
|
|
87
|
+
|
|
88
|
+
# Config + Validation
|
|
89
|
+
cfg = load_config(".env", env_prefix="APP_")
|
|
90
|
+
email = is_email(cfg.get("user_email", ""))
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Design Philosophy
|
|
96
|
+
|
|
97
|
+
- **Zero hard dependencies** — works out of the box
|
|
98
|
+
- **First-class async** support
|
|
99
|
+
- **Excellent developer experience**
|
|
100
|
+
- **Fully typed** (ships with `py.typed`)
|
|
101
|
+
- **CLI & automation focused**
|
|
102
|
+
- **Small and readable** source
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
git clone https://github.com/VikasPatel22/everynow.git
|
|
110
|
+
cd everynow
|
|
111
|
+
pip install -e ".[dev]"
|
|
112
|
+
pytest
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## License
|
|
118
|
+
|
|
119
|
+
MIT © Vikas Patel
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
everynow — Modern everyday Python utilities (maxed out)
|
|
3
|
+
Lightweight • Fully typed • Async-capable • Zero hard dependencies
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .config import Config, load_config, auto_config
|
|
7
|
+
from .retry import retry, aretry, RetryError, retry_call
|
|
8
|
+
from .terminal import (
|
|
9
|
+
progress, spinner, success, error, warning, info, debug, status,
|
|
10
|
+
table, confirm, ask, rule, clear,
|
|
11
|
+
)
|
|
12
|
+
from .cache import cache, acache, Cache, cached_property
|
|
13
|
+
from .files import (
|
|
14
|
+
ensure_dir, safe_write, atomic_write, human_size, find_files,
|
|
15
|
+
read_text, write_json, read_json, file_hash, temp_dir,
|
|
16
|
+
)
|
|
17
|
+
from .log import get_logger, setup_logging
|
|
18
|
+
from .http import get, post, request, aget, apost, arequest, HttpError, HttpResponse
|
|
19
|
+
from .validate import (
|
|
20
|
+
require, one_of, between, is_email, is_url, is_phone, length, matches, ensure,
|
|
21
|
+
)
|
|
22
|
+
from .timing import Timer, timer, timed, benchmark
|
|
23
|
+
from .rate import RateLimiter, rate_limit
|
|
24
|
+
|
|
25
|
+
__version__ = "0.4.0"
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
# config
|
|
29
|
+
"Config", "load_config", "auto_config",
|
|
30
|
+
# retry
|
|
31
|
+
"retry", "aretry", "retry_call", "RetryError",
|
|
32
|
+
# terminal
|
|
33
|
+
"progress", "spinner", "success", "error", "warning", "info", "debug",
|
|
34
|
+
"status", "table", "confirm", "ask", "rule", "clear",
|
|
35
|
+
# cache
|
|
36
|
+
"cache", "acache", "Cache", "cached_property",
|
|
37
|
+
# files
|
|
38
|
+
"ensure_dir", "safe_write", "atomic_write", "human_size", "find_files",
|
|
39
|
+
"read_text", "write_json", "read_json", "file_hash", "temp_dir",
|
|
40
|
+
# log
|
|
41
|
+
"get_logger", "setup_logging",
|
|
42
|
+
# http
|
|
43
|
+
"get", "post", "request", "aget", "apost", "arequest", "HttpError", "HttpResponse",
|
|
44
|
+
# validate
|
|
45
|
+
"require", "one_of", "between", "is_email", "is_url", "is_phone", "length", "matches", "ensure",
|
|
46
|
+
# timing
|
|
47
|
+
"Timer", "timer", "timed", "benchmark",
|
|
48
|
+
# rate
|
|
49
|
+
"RateLimiter", "rate_limit",
|
|
50
|
+
]
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TTL cache — sync + async support + optional disk persistence.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import functools
|
|
8
|
+
import hashlib
|
|
9
|
+
import pickle
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Callable, Optional, TypeVar, Union
|
|
13
|
+
|
|
14
|
+
F = TypeVar("F", bound=Callable[..., Any])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Cache:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
ttl: Optional[float] = 300.0,
|
|
21
|
+
maxsize: int = 512,
|
|
22
|
+
persist_path: Optional[Union[str, Path]] = None,
|
|
23
|
+
):
|
|
24
|
+
self.ttl = ttl
|
|
25
|
+
self.maxsize = maxsize
|
|
26
|
+
self.persist_path = Path(persist_path) if persist_path else None
|
|
27
|
+
self._store: dict[str, tuple[Any, Optional[float]]] = {}
|
|
28
|
+
if self.persist_path and self.persist_path.exists():
|
|
29
|
+
self._load()
|
|
30
|
+
|
|
31
|
+
def _key(self, *parts: Any) -> str:
|
|
32
|
+
return hashlib.sha256(pickle.dumps(parts, protocol=4)).hexdigest()
|
|
33
|
+
|
|
34
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
35
|
+
item = self._store.get(key)
|
|
36
|
+
if item is None:
|
|
37
|
+
return default
|
|
38
|
+
value, expires = item
|
|
39
|
+
if expires is not None and time.time() > expires:
|
|
40
|
+
self._store.pop(key, None)
|
|
41
|
+
return default
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
def set(self, key: str, value: Any, ttl: Optional[float] = None) -> None:
|
|
45
|
+
effective = ttl if ttl is not None else self.ttl
|
|
46
|
+
expires = time.time() + effective if effective is not None else None
|
|
47
|
+
self._store[key] = (value, expires)
|
|
48
|
+
if len(self._store) > self.maxsize:
|
|
49
|
+
self._store.pop(next(iter(self._store)), None)
|
|
50
|
+
if self.persist_path:
|
|
51
|
+
self._save()
|
|
52
|
+
|
|
53
|
+
def clear(self) -> None:
|
|
54
|
+
self._store.clear()
|
|
55
|
+
if self.persist_path and self.persist_path.exists():
|
|
56
|
+
try:
|
|
57
|
+
self.persist_path.unlink()
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
def __len__(self) -> int:
|
|
62
|
+
return len(self._store)
|
|
63
|
+
|
|
64
|
+
def _save(self) -> None:
|
|
65
|
+
if not self.persist_path:
|
|
66
|
+
return
|
|
67
|
+
self.persist_path.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
now = time.time()
|
|
69
|
+
clean = {k: v for k, v in self._store.items() if v[1] is None or v[1] > now}
|
|
70
|
+
try:
|
|
71
|
+
with open(self.persist_path, "wb") as f:
|
|
72
|
+
pickle.dump(clean, f, protocol=4)
|
|
73
|
+
except Exception:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
def _load(self) -> None:
|
|
77
|
+
try:
|
|
78
|
+
with open(self.persist_path, "rb") as f:
|
|
79
|
+
data = pickle.load(f)
|
|
80
|
+
now = time.time()
|
|
81
|
+
self._store = {k: v for k, v in data.items() if v[1] is None or v[1] > now}
|
|
82
|
+
except Exception:
|
|
83
|
+
self._store = {}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_default = Cache(ttl=300.0)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cache(
|
|
90
|
+
ttl: Optional[float] = 300.0,
|
|
91
|
+
key: Optional[Callable[..., str]] = None,
|
|
92
|
+
cache_instance: Optional[Cache] = None,
|
|
93
|
+
) -> Callable[[F], F]:
|
|
94
|
+
"""Sync cache decorator."""
|
|
95
|
+
store = cache_instance or _default
|
|
96
|
+
|
|
97
|
+
def decorator(func: F) -> F:
|
|
98
|
+
@functools.wraps(func)
|
|
99
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
100
|
+
k = key(*args, **kwargs) if key else store._key(
|
|
101
|
+
func.__module__, func.__qualname__, args, tuple(sorted(kwargs.items()))
|
|
102
|
+
)
|
|
103
|
+
hit = store.get(k)
|
|
104
|
+
if hit is not None:
|
|
105
|
+
return hit
|
|
106
|
+
result = func(*args, **kwargs)
|
|
107
|
+
store.set(k, result, ttl=ttl)
|
|
108
|
+
return result
|
|
109
|
+
|
|
110
|
+
wrapper.cache_clear = store.clear # type: ignore
|
|
111
|
+
return wrapper # type: ignore
|
|
112
|
+
|
|
113
|
+
return decorator
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def acache(
|
|
117
|
+
ttl: Optional[float] = 300.0,
|
|
118
|
+
key: Optional[Callable[..., str]] = None,
|
|
119
|
+
cache_instance: Optional[Cache] = None,
|
|
120
|
+
) -> Callable[[F], F]:
|
|
121
|
+
"""Async cache decorator."""
|
|
122
|
+
store = cache_instance or _default
|
|
123
|
+
|
|
124
|
+
def decorator(func: F) -> F:
|
|
125
|
+
@functools.wraps(func)
|
|
126
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
127
|
+
k = key(*args, **kwargs) if key else store._key(
|
|
128
|
+
func.__module__, func.__qualname__, args, tuple(sorted(kwargs.items()))
|
|
129
|
+
)
|
|
130
|
+
hit = store.get(k)
|
|
131
|
+
if hit is not None:
|
|
132
|
+
return hit
|
|
133
|
+
result = await func(*args, **kwargs)
|
|
134
|
+
store.set(k, result, ttl=ttl)
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
wrapper.cache_clear = store.clear # type: ignore
|
|
138
|
+
return wrapper # type: ignore
|
|
139
|
+
|
|
140
|
+
return decorator
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cached_property(func: Callable[..., Any]) -> property:
|
|
144
|
+
attr = f"_cached_{func.__name__}"
|
|
145
|
+
|
|
146
|
+
@functools.wraps(func)
|
|
147
|
+
def getter(self: Any) -> Any:
|
|
148
|
+
if not hasattr(self, attr):
|
|
149
|
+
setattr(self, attr, func(self))
|
|
150
|
+
return getattr(self, attr)
|
|
151
|
+
|
|
152
|
+
return property(getter)
|