pyBiocFileCache 0.7.0__py3-none-any.whl → 0.8.0__py3-none-any.whl
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.
- pybiocfilecache/cache.py +316 -124
- pybiocfilecache/config.py +1 -2
- pybiocfilecache/models.py +2 -1
- pybiocfilecache/py.typed +0 -0
- pybiocfilecache/utils.py +15 -7
- pybiocfilecache-0.8.0.dist-info/METADATA +59 -0
- pybiocfilecache-0.8.0.dist-info/RECORD +12 -0
- {pybiocfilecache-0.7.0.dist-info → pybiocfilecache-0.8.0.dist-info}/WHEEL +1 -2
- pybiocfilecache-0.7.0.dist-info/METADATA +0 -117
- pybiocfilecache-0.7.0.dist-info/RECORD +0 -12
- pybiocfilecache-0.7.0.dist-info/top_level.txt +0 -1
- {pybiocfilecache-0.7.0.dist-info → pybiocfilecache-0.8.0.dist-info}/licenses/AUTHORS.md +0 -0
- {pybiocfilecache-0.7.0.dist-info → pybiocfilecache-0.8.0.dist-info}/licenses/LICENSE.txt +0 -0
pybiocfilecache/cache.py
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import logging
|
|
4
|
+
import shutil
|
|
5
|
+
from collections.abc import Iterator
|
|
2
6
|
from contextlib import contextmanager
|
|
3
|
-
from datetime import datetime
|
|
7
|
+
from datetime import datetime, timezone
|
|
4
8
|
from pathlib import Path
|
|
5
9
|
from time import sleep, time
|
|
6
|
-
from typing import Any,
|
|
10
|
+
from typing import Any, Literal
|
|
7
11
|
|
|
8
12
|
from biocframe import BiocFrame
|
|
9
13
|
from sqlalchemy import create_engine, func, text
|
|
@@ -30,6 +34,19 @@ __license__ = "MIT"
|
|
|
30
34
|
logger = logging.getLogger(__name__)
|
|
31
35
|
|
|
32
36
|
|
|
37
|
+
def _now() -> datetime:
|
|
38
|
+
"""Return current UTC time as a naive datetime matching SQLite CURRENT_TIMESTAMP."""
|
|
39
|
+
return datetime.now(timezone.utc).replace(tzinfo=None)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _normalize_datetime(dt: datetime | None) -> datetime | None:
|
|
43
|
+
"""Normalize an optional datetime to naive UTC."""
|
|
44
|
+
if dt is not None and dt.tzinfo is not None:
|
|
45
|
+
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
|
46
|
+
|
|
47
|
+
return dt
|
|
48
|
+
|
|
49
|
+
|
|
33
50
|
class BiocFileCache:
|
|
34
51
|
"""Enhanced file caching module.
|
|
35
52
|
|
|
@@ -39,7 +56,7 @@ class BiocFileCache:
|
|
|
39
56
|
- Cleanup of expired resources
|
|
40
57
|
"""
|
|
41
58
|
|
|
42
|
-
def __init__(self, cache_dir:
|
|
59
|
+
def __init__(self, cache_dir: str | Path | None = None, config: CacheConfig | None = None):
|
|
43
60
|
"""Initialize cache with optional configuration.
|
|
44
61
|
|
|
45
62
|
Args:
|
|
@@ -63,7 +80,7 @@ class BiocFileCache:
|
|
|
63
80
|
if db_schema_version != SCHEMA_VERSION:
|
|
64
81
|
raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
|
|
65
82
|
|
|
66
|
-
self._last_cleanup =
|
|
83
|
+
self._last_cleanup = _now()
|
|
67
84
|
|
|
68
85
|
def _setup_cache_dir(self) -> bool:
|
|
69
86
|
if not self.config.cache_dir.exists():
|
|
@@ -84,6 +101,7 @@ class BiocFileCache:
|
|
|
84
101
|
self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
|
|
85
102
|
|
|
86
103
|
with self.engine.connect() as conn:
|
|
104
|
+
self._ensure_autoincrement(conn)
|
|
87
105
|
result = conn.execute(
|
|
88
106
|
text("""
|
|
89
107
|
SELECT value FROM metadata
|
|
@@ -106,7 +124,52 @@ class BiocFileCache:
|
|
|
106
124
|
|
|
107
125
|
return SCHEMA_VERSION
|
|
108
126
|
|
|
109
|
-
def
|
|
127
|
+
def _ensure_autoincrement(self, conn) -> None:
|
|
128
|
+
"""Migrate legacy resource table without AUTOINCREMENT so SQLite never reuses deleted row IDs."""
|
|
129
|
+
row = conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='resource'")).fetchone()
|
|
130
|
+
if row is None or not row[0] or "AUTOINCREMENT" in row[0].upper():
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
dup_count = conn.execute(
|
|
134
|
+
text("SELECT COUNT(*) - COUNT(DISTINCT rid) FROM resource WHERE rid IS NOT NULL")
|
|
135
|
+
).scalar()
|
|
136
|
+
unique_clause = ", UNIQUE (rid)" if not dup_count else ""
|
|
137
|
+
|
|
138
|
+
cols = "id, rid, rname, create_time, access_time, rpath, rtype, fpath, last_modified_time, etag, expires"
|
|
139
|
+
conn.execute(
|
|
140
|
+
text(
|
|
141
|
+
f"""
|
|
142
|
+
CREATE TABLE resource_new (
|
|
143
|
+
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
|
144
|
+
rid TEXT,
|
|
145
|
+
rname TEXT,
|
|
146
|
+
create_time DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
|
147
|
+
access_time DATETIME DEFAULT (CURRENT_TIMESTAMP),
|
|
148
|
+
rpath TEXT,
|
|
149
|
+
rtype TEXT,
|
|
150
|
+
fpath TEXT,
|
|
151
|
+
last_modified_time DATETIME,
|
|
152
|
+
etag TEXT,
|
|
153
|
+
expires DATETIME{unique_clause}
|
|
154
|
+
)
|
|
155
|
+
"""
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
conn.execute(text(f"INSERT INTO resource_new ({cols}) SELECT {cols} FROM resource"))
|
|
159
|
+
conn.execute(text("DROP TABLE resource"))
|
|
160
|
+
conn.execute(text("ALTER TABLE resource_new RENAME TO resource"))
|
|
161
|
+
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_resource_id ON resource (id)"))
|
|
162
|
+
conn.commit()
|
|
163
|
+
|
|
164
|
+
def _resolve_rpath(self, rpath: str, rtype: str | None) -> Path:
|
|
165
|
+
"""Resolve a stored resource path against cache_dir when relative."""
|
|
166
|
+
path = Path(rpath)
|
|
167
|
+
if rtype in ("relative", "web") and not path.is_absolute():
|
|
168
|
+
return self.config.cache_dir / path
|
|
169
|
+
|
|
170
|
+
return path
|
|
171
|
+
|
|
172
|
+
def _get_detached_resource(self, session: Session, obj: Resource | Metadata) -> dict | None:
|
|
110
173
|
"""Get a detached copy of a resource."""
|
|
111
174
|
if obj is None:
|
|
112
175
|
return None
|
|
@@ -114,13 +177,12 @@ class BiocFileCache:
|
|
|
114
177
|
session.expunge(obj)
|
|
115
178
|
obj_dict = obj.to_dict()
|
|
116
179
|
|
|
117
|
-
if isinstance(obj, Resource):
|
|
118
|
-
|
|
119
|
-
obj_dict["rpath"] = f"{self.config.cache_dir}/{obj_dict['rpath']}"
|
|
180
|
+
if isinstance(obj, Resource) and obj_dict["rtype"] in ("relative", "web"):
|
|
181
|
+
obj_dict["rpath"] = str(self._resolve_rpath(obj_dict["rpath"], obj_dict["rtype"]))
|
|
120
182
|
|
|
121
183
|
return obj_dict
|
|
122
184
|
|
|
123
|
-
def __enter__(self) ->
|
|
185
|
+
def __enter__(self) -> BiocFileCache:
|
|
124
186
|
return self
|
|
125
187
|
|
|
126
188
|
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
@@ -161,7 +223,7 @@ class BiocFileCache:
|
|
|
161
223
|
if self.config.cleanup_interval is None:
|
|
162
224
|
return False
|
|
163
225
|
|
|
164
|
-
return
|
|
226
|
+
return _now() - self._last_cleanup > self.config.cleanup_interval
|
|
165
227
|
|
|
166
228
|
def cleanup(self) -> int:
|
|
167
229
|
"""Remove expired resources from the cache.
|
|
@@ -170,27 +232,25 @@ class BiocFileCache:
|
|
|
170
232
|
Number of resources removed.
|
|
171
233
|
|
|
172
234
|
Note:
|
|
173
|
-
-
|
|
235
|
+
- Runs whenever called explicitly, even if `cleanup_interval` is None.
|
|
174
236
|
- Only removes resources with non-None expiration dates.
|
|
175
237
|
"""
|
|
176
|
-
if not any([self.config.cleanup_interval, self._should_cleanup()]):
|
|
177
|
-
return 0 # Early return if automatic cleanup is disabled
|
|
178
|
-
|
|
179
238
|
removed = 0
|
|
239
|
+
now = _now()
|
|
180
240
|
with self.get_session() as session:
|
|
181
241
|
# Only query resources that have expiration dates
|
|
182
242
|
expired = (
|
|
183
243
|
session.query(Resource)
|
|
184
244
|
.filter(
|
|
185
245
|
Resource.expires.isnot(None), # Only check resources with expiration
|
|
186
|
-
Resource.expires <
|
|
246
|
+
Resource.expires < now,
|
|
187
247
|
)
|
|
188
248
|
.all()
|
|
189
249
|
)
|
|
190
250
|
|
|
191
251
|
for resource in expired:
|
|
192
252
|
try:
|
|
193
|
-
|
|
253
|
+
self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
|
|
194
254
|
session.delete(resource)
|
|
195
255
|
removed += 1
|
|
196
256
|
except Exception as e:
|
|
@@ -198,15 +258,22 @@ class BiocFileCache:
|
|
|
198
258
|
|
|
199
259
|
session.commit()
|
|
200
260
|
|
|
201
|
-
self._last_cleanup =
|
|
261
|
+
self._last_cleanup = now
|
|
202
262
|
return removed
|
|
203
263
|
|
|
204
264
|
###############################
|
|
205
265
|
######>> get resources <<######
|
|
206
266
|
###############################
|
|
207
267
|
|
|
208
|
-
def get(
|
|
209
|
-
|
|
268
|
+
def get(
|
|
269
|
+
self,
|
|
270
|
+
rname: str | None = None,
|
|
271
|
+
rid: str | None = None,
|
|
272
|
+
wait: bool = True,
|
|
273
|
+
timeout: float = 30,
|
|
274
|
+
update_access_time: bool = True,
|
|
275
|
+
) -> dict | None:
|
|
276
|
+
"""Get resource by name or id from cache.
|
|
210
277
|
|
|
211
278
|
Args:
|
|
212
279
|
rname:
|
|
@@ -215,39 +282,123 @@ class BiocFileCache:
|
|
|
215
282
|
rid:
|
|
216
283
|
Resource id to search by.
|
|
217
284
|
|
|
285
|
+
wait:
|
|
286
|
+
Whether to wait for the cached file to exist on disk.
|
|
287
|
+
If False, returns the registered record immediately even if
|
|
288
|
+
the file is missing. Defaults to True.
|
|
289
|
+
|
|
290
|
+
timeout:
|
|
291
|
+
Maximum seconds to wait when `wait=True`. Defaults to 30.
|
|
292
|
+
|
|
293
|
+
update_access_time:
|
|
294
|
+
Whether to update `access_time` in the database when the
|
|
295
|
+
cached file exists. Set to False for read-only lookups.
|
|
296
|
+
Defaults to True.
|
|
297
|
+
|
|
218
298
|
"""
|
|
219
299
|
if rname is None and rid is None:
|
|
220
300
|
raise ValueError("either 'rname' or 'rid' must be provided.")
|
|
221
301
|
|
|
222
302
|
with self.get_session() as session:
|
|
223
|
-
if
|
|
224
|
-
resource = session.query(Resource).filter(Resource.rname == rname).first()
|
|
225
|
-
elif rid is not None:
|
|
303
|
+
if rid is not None:
|
|
226
304
|
resource = session.query(Resource).filter(Resource.rid == rid).first()
|
|
305
|
+
else:
|
|
306
|
+
resource = session.query(Resource).filter(Resource.rname == rname).first()
|
|
227
307
|
|
|
228
308
|
if resource is not None:
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
309
|
+
resolved_path = self._resolve_rpath(resource.rpath, resource.rtype)
|
|
310
|
+
if wait:
|
|
311
|
+
start = time()
|
|
312
|
+
while not resolved_path.exists():
|
|
313
|
+
if time() - start >= timeout:
|
|
314
|
+
identifier = rid if rid is not None else rname
|
|
315
|
+
raise TimeoutError(
|
|
316
|
+
f"For resource: '{identifier}' the rpath does not exist after {timeout} seconds."
|
|
317
|
+
)
|
|
318
|
+
sleep(0.1)
|
|
319
|
+
|
|
320
|
+
if update_access_time and resolved_path.exists():
|
|
321
|
+
resource.access_time = _now()
|
|
322
|
+
session.commit()
|
|
323
|
+
|
|
240
324
|
return self._get_detached_resource(session, resource)
|
|
241
325
|
|
|
242
326
|
return None
|
|
243
327
|
|
|
328
|
+
def _add_to_session(
|
|
329
|
+
self,
|
|
330
|
+
session: Session,
|
|
331
|
+
rname: str,
|
|
332
|
+
fpath: str | Path,
|
|
333
|
+
rtype: Literal["local", "web", "relative"] = "relative",
|
|
334
|
+
action: Literal["copy", "move", "asis"] = "copy",
|
|
335
|
+
expires: datetime | None = None,
|
|
336
|
+
download: bool = True,
|
|
337
|
+
ext: bool = True,
|
|
338
|
+
) -> tuple[Resource, Path | None]:
|
|
339
|
+
"""Insert a resource record and store its file within an active session."""
|
|
340
|
+
if session.query(Resource).filter(Resource.rname == rname).first() is not None:
|
|
341
|
+
raise FileExistsError(f"Resource '{rname}' already exists")
|
|
342
|
+
|
|
343
|
+
fpath_val = Path(fpath) if rtype != "web" else fpath
|
|
344
|
+
tmp_dir: Path | None = None
|
|
345
|
+
|
|
346
|
+
if rtype == "web":
|
|
347
|
+
outpath = download_web_file(str(fpath_val), None, download)
|
|
348
|
+
tmp_dir = outpath.parent
|
|
349
|
+
action = "copy"
|
|
350
|
+
else:
|
|
351
|
+
outpath = Path(fpath_val)
|
|
352
|
+
|
|
353
|
+
if action == "asis":
|
|
354
|
+
if rtype != "local":
|
|
355
|
+
logger.warning("If action='asis', rtype must be 'local'.")
|
|
356
|
+
rtype = "local"
|
|
357
|
+
elif rtype == "local":
|
|
358
|
+
rtype = "relative"
|
|
359
|
+
|
|
360
|
+
uuid_str = generate_uuid()
|
|
361
|
+
rpath = f"{uuid_str}_{outpath.name if ext else outpath.stem}" if action != "asis" else str(fpath_val)
|
|
362
|
+
|
|
363
|
+
resource = Resource(
|
|
364
|
+
rid=None,
|
|
365
|
+
rname=rname,
|
|
366
|
+
rpath=str(rpath),
|
|
367
|
+
rtype=rtype,
|
|
368
|
+
fpath=str(fpath_val),
|
|
369
|
+
expires=_normalize_datetime(expires),
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
copied_target: Path | None = None
|
|
373
|
+
try:
|
|
374
|
+
session.add(resource)
|
|
375
|
+
session.flush()
|
|
376
|
+
resource.rid = generate_id(resource.id)
|
|
377
|
+
|
|
378
|
+
target_path = self._resolve_rpath(resource.rpath, resource.rtype)
|
|
379
|
+
copy_or_move(outpath, target_path, rname, action, False)
|
|
380
|
+
if action != "asis":
|
|
381
|
+
copied_target = target_path
|
|
382
|
+
|
|
383
|
+
resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
|
|
384
|
+
|
|
385
|
+
return resource, copied_target
|
|
386
|
+
except Exception:
|
|
387
|
+
if copied_target is not None and copied_target.exists():
|
|
388
|
+
copied_target.unlink(missing_ok=True)
|
|
389
|
+
|
|
390
|
+
raise
|
|
391
|
+
finally:
|
|
392
|
+
if tmp_dir is not None:
|
|
393
|
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
|
394
|
+
|
|
244
395
|
def add(
|
|
245
396
|
self,
|
|
246
397
|
rname: str,
|
|
247
|
-
fpath:
|
|
398
|
+
fpath: str | Path,
|
|
248
399
|
rtype: Literal["local", "web", "relative"] = "relative",
|
|
249
400
|
action: Literal["copy", "move", "asis"] = "copy",
|
|
250
|
-
expires:
|
|
401
|
+
expires: datetime | None = None,
|
|
251
402
|
download: bool = True,
|
|
252
403
|
ext: bool = True,
|
|
253
404
|
) -> dict:
|
|
@@ -263,7 +414,7 @@ class BiocFileCache:
|
|
|
263
414
|
rtype:
|
|
264
415
|
Type of resource.
|
|
265
416
|
One of ``local``, ``web``, or ``relative``.
|
|
266
|
-
Defaults to ``
|
|
417
|
+
Defaults to ``relative``.
|
|
267
418
|
|
|
268
419
|
action:
|
|
269
420
|
How to handle the file ("copy", "move", or "asis").
|
|
@@ -284,80 +435,65 @@ class BiocFileCache:
|
|
|
284
435
|
Returns:
|
|
285
436
|
The `Resource` object added to the cache as dictionary.
|
|
286
437
|
"""
|
|
287
|
-
# self._validate_rname(rname)
|
|
288
|
-
fpath = Path(fpath) if rtype != "web" else fpath
|
|
289
|
-
|
|
290
|
-
if self.get(rname) is not None:
|
|
291
|
-
raise FileExistsError(f"Resource '{rname}' already exists")
|
|
292
|
-
|
|
293
|
-
if rtype == "web":
|
|
294
|
-
outpath = download_web_file(fpath, Path(fpath).name, download)
|
|
295
|
-
action = "copy"
|
|
296
|
-
else:
|
|
297
|
-
outpath = Path(fpath)
|
|
298
|
-
|
|
299
|
-
if action == "asis":
|
|
300
|
-
logger.warning("If action='asis', rtype must be 'local'.")
|
|
301
|
-
rtype = "local"
|
|
302
|
-
|
|
303
|
-
# Generate paths and check size
|
|
304
|
-
rid = generate_id(size=len(self))
|
|
305
|
-
uuid = generate_uuid()
|
|
306
|
-
rpath = f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath
|
|
307
|
-
|
|
308
|
-
# Create resource record
|
|
309
|
-
resource = Resource(
|
|
310
|
-
rid=rid,
|
|
311
|
-
rname=rname,
|
|
312
|
-
rpath=str(rpath),
|
|
313
|
-
rtype=rtype,
|
|
314
|
-
fpath=str(fpath),
|
|
315
|
-
expires=expires,
|
|
316
|
-
)
|
|
317
|
-
|
|
318
|
-
# Store file and update database
|
|
319
438
|
with self.get_session() as session:
|
|
320
|
-
session.add(resource)
|
|
321
|
-
session.commit()
|
|
322
|
-
|
|
323
439
|
try:
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
440
|
+
resource, _ = self._add_to_session(
|
|
441
|
+
session=session,
|
|
442
|
+
rname=rname,
|
|
443
|
+
fpath=fpath,
|
|
444
|
+
rtype=rtype,
|
|
445
|
+
action=action,
|
|
446
|
+
expires=expires,
|
|
447
|
+
download=download,
|
|
448
|
+
ext=ext,
|
|
449
|
+
)
|
|
328
450
|
session.commit()
|
|
329
|
-
result = self._get_detached_resource(session, resource)
|
|
330
|
-
return result
|
|
331
451
|
|
|
452
|
+
return self._get_detached_resource(session, resource)
|
|
453
|
+
except FileExistsError:
|
|
454
|
+
session.rollback()
|
|
455
|
+
raise
|
|
332
456
|
except Exception as e:
|
|
333
|
-
session.
|
|
334
|
-
session.commit()
|
|
457
|
+
session.rollback()
|
|
335
458
|
raise Exception("Failed to add resource") from e
|
|
336
459
|
|
|
337
|
-
def add_batch(self, resources:
|
|
460
|
+
def add_batch(self, resources: list[dict[str, Any]]) -> BiocFrame:
|
|
338
461
|
"""Add multiple resources in a single transaction.
|
|
339
462
|
|
|
340
463
|
Args:
|
|
341
464
|
resources:
|
|
342
465
|
List of resources to add.
|
|
343
466
|
"""
|
|
344
|
-
|
|
467
|
+
added_resources: list[Resource] = []
|
|
468
|
+
copied_targets: list[Path] = []
|
|
345
469
|
with self.get_session() as session:
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
resource = self.
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
470
|
+
try:
|
|
471
|
+
for resource_info in resources:
|
|
472
|
+
resource, copied_target = self._add_to_session(session=session, **resource_info)
|
|
473
|
+
added_resources.append(resource)
|
|
474
|
+
if copied_target is not None:
|
|
475
|
+
copied_targets.append(copied_target)
|
|
476
|
+
|
|
477
|
+
session.commit()
|
|
478
|
+
|
|
479
|
+
return BiocFrame(
|
|
480
|
+
convert_to_columnar([self._get_detached_resource(session, r) for r in added_resources])
|
|
481
|
+
)
|
|
482
|
+
except Exception as e:
|
|
483
|
+
logger.error("Failed to add batch of resources", exc_info=e)
|
|
484
|
+
session.rollback()
|
|
485
|
+
|
|
486
|
+
for target in copied_targets:
|
|
487
|
+
target.unlink(missing_ok=True)
|
|
488
|
+
|
|
489
|
+
raise
|
|
355
490
|
|
|
356
491
|
def update(
|
|
357
492
|
self,
|
|
358
|
-
rname: str,
|
|
359
|
-
fpath:
|
|
493
|
+
rname: str | None = None,
|
|
494
|
+
fpath: str | Path = None,
|
|
360
495
|
action: Literal["copy", "move", "asis"] = "copy",
|
|
496
|
+
rid: str | None = None,
|
|
361
497
|
) -> dict:
|
|
362
498
|
"""Update an existing resource.
|
|
363
499
|
|
|
@@ -372,36 +508,62 @@ class BiocFileCache:
|
|
|
372
508
|
Either ``copy``, ``move`` or ``asis``.
|
|
373
509
|
Defaults to ``copy``.
|
|
374
510
|
|
|
511
|
+
rid:
|
|
512
|
+
Optional resource id to identify the resource.
|
|
513
|
+
|
|
375
514
|
Returns:
|
|
376
515
|
Updated `Resource` object as dictionary.
|
|
377
516
|
|
|
378
517
|
"""
|
|
518
|
+
if rname is None and rid is None:
|
|
519
|
+
raise ValueError("either 'rname' or 'rid' must be provided.")
|
|
520
|
+
|
|
521
|
+
if fpath is None:
|
|
522
|
+
raise ValueError("'fpath' must be provided.")
|
|
523
|
+
|
|
379
524
|
fpath = Path(fpath)
|
|
380
525
|
if not fpath.exists():
|
|
381
526
|
raise FileNotFoundError(f"File '{fpath}' does not exist")
|
|
382
527
|
|
|
383
528
|
with self.get_session() as session:
|
|
384
|
-
|
|
529
|
+
if rid is not None:
|
|
530
|
+
resource = session.query(Resource).filter(Resource.rid == rid).first()
|
|
531
|
+
else:
|
|
532
|
+
resource = session.query(Resource).filter(Resource.rname == rname).first()
|
|
385
533
|
|
|
386
534
|
if resource is None:
|
|
535
|
+
if rname is None:
|
|
536
|
+
raise KeyError(f"Resource with rid '{rid}' not found")
|
|
387
537
|
return self.add(rname=rname, fpath=fpath, action=action)
|
|
388
538
|
|
|
389
|
-
old_path = Path(resource.rpath)
|
|
390
539
|
try:
|
|
391
|
-
|
|
540
|
+
if action == "asis":
|
|
541
|
+
resource.rpath = str(fpath)
|
|
542
|
+
resource.rtype = "local"
|
|
543
|
+
target_path = fpath
|
|
544
|
+
else:
|
|
545
|
+
if resource.rtype == "local":
|
|
546
|
+
resource.rtype = "relative"
|
|
547
|
+
resource.rpath = f"{generate_uuid()}_{fpath.name}"
|
|
548
|
+
|
|
549
|
+
target_path = self._resolve_rpath(resource.rpath, resource.rtype)
|
|
550
|
+
copy_or_move(fpath, target_path, resource.rname, action, False)
|
|
392
551
|
|
|
393
|
-
resource.
|
|
394
|
-
resource.
|
|
552
|
+
resource.fpath = str(fpath)
|
|
553
|
+
resource.last_modified_time = _now()
|
|
554
|
+
resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
|
|
395
555
|
|
|
396
556
|
session.commit()
|
|
557
|
+
|
|
397
558
|
return self._get_detached_resource(session, resource)
|
|
398
559
|
|
|
399
560
|
except Exception as e:
|
|
400
561
|
session.rollback()
|
|
562
|
+
|
|
401
563
|
raise Exception("Failed to update resource") from e
|
|
402
564
|
|
|
403
|
-
def remove(self, rname: str) -> None:
|
|
404
|
-
"""Remove a resource from cache by name.
|
|
565
|
+
def remove(self, rname: str | None = None, rid: str | None = None) -> None:
|
|
566
|
+
"""Remove a resource from cache by name or id.
|
|
405
567
|
|
|
406
568
|
Removes both the cached file and its database entry.
|
|
407
569
|
|
|
@@ -409,16 +571,25 @@ class BiocFileCache:
|
|
|
409
571
|
rname:
|
|
410
572
|
Name to identify the resource in cache.
|
|
411
573
|
|
|
574
|
+
rid:
|
|
575
|
+
Resource id to identify the resource in cache.
|
|
576
|
+
|
|
412
577
|
Raises:
|
|
413
578
|
Exception: If resource removal fails
|
|
414
579
|
"""
|
|
580
|
+
if rname is None and rid is None:
|
|
581
|
+
raise ValueError("either 'rname' or 'rid' must be provided.")
|
|
582
|
+
|
|
415
583
|
with self.get_session() as session:
|
|
416
|
-
|
|
584
|
+
if rid is not None:
|
|
585
|
+
resource = session.query(Resource).filter(Resource.rid == rid).first()
|
|
586
|
+
else:
|
|
587
|
+
resource = session.query(Resource).filter(Resource.rname == rname).first()
|
|
417
588
|
|
|
418
589
|
if resource is not None:
|
|
419
590
|
try:
|
|
420
591
|
# Try to remove the file first
|
|
421
|
-
rpath =
|
|
592
|
+
rpath = self._resolve_rpath(resource.rpath, resource.rtype)
|
|
422
593
|
if rpath.exists():
|
|
423
594
|
rpath.unlink()
|
|
424
595
|
|
|
@@ -428,9 +599,10 @@ class BiocFileCache:
|
|
|
428
599
|
|
|
429
600
|
except Exception as e:
|
|
430
601
|
session.rollback()
|
|
431
|
-
|
|
602
|
+
identifier = rid if rid is not None else rname
|
|
603
|
+
raise Exception(f"Failed to remove resource '{identifier}'") from e
|
|
432
604
|
|
|
433
|
-
def list_resources(self, rtype:
|
|
605
|
+
def list_resources(self, rtype: str | None = None, expired: bool | None = None) -> BiocFrame:
|
|
434
606
|
"""List resources in the cache with optional filtering.
|
|
435
607
|
|
|
436
608
|
Args:
|
|
@@ -454,38 +626,52 @@ class BiocFileCache:
|
|
|
454
626
|
if rtype:
|
|
455
627
|
query = query.filter(Resource.rtype == rtype)
|
|
456
628
|
if expired is not None:
|
|
629
|
+
now = _now()
|
|
457
630
|
if expired:
|
|
458
631
|
query = query.filter(
|
|
459
632
|
Resource.expires.isnot(None), # Only check resources with expiration
|
|
460
|
-
Resource.expires <
|
|
633
|
+
Resource.expires < now,
|
|
461
634
|
)
|
|
462
635
|
else:
|
|
463
636
|
query = query.filter(
|
|
464
637
|
(Resource.expires.is_(None)) # Never expires
|
|
465
|
-
| (Resource.expires >
|
|
638
|
+
| (Resource.expires > now) # Not yet expired
|
|
466
639
|
)
|
|
467
640
|
|
|
468
641
|
resources = query.all()
|
|
469
642
|
return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
|
|
470
643
|
|
|
471
|
-
def validate_resource(self, resource: Resource) -> bool:
|
|
644
|
+
def validate_resource(self, resource: Resource | dict) -> bool:
|
|
472
645
|
"""Validate resource integrity.
|
|
473
646
|
|
|
474
647
|
Args:
|
|
475
648
|
resource:
|
|
476
|
-
Resource to validate.
|
|
649
|
+
Resource ORM object or dictionary to validate.
|
|
477
650
|
|
|
478
651
|
Returns:
|
|
479
652
|
True if resource is valid, False otherwise.
|
|
480
653
|
"""
|
|
481
|
-
if
|
|
654
|
+
if isinstance(resource, dict):
|
|
655
|
+
etag = resource.get("etag")
|
|
656
|
+
rpath = resource.get("rpath")
|
|
657
|
+
rtype = resource.get("rtype")
|
|
658
|
+
rname = resource.get("rname")
|
|
659
|
+
else:
|
|
660
|
+
etag = resource.etag
|
|
661
|
+
rpath = resource.rpath
|
|
662
|
+
rtype = resource.rtype
|
|
663
|
+
rname = resource.rname
|
|
664
|
+
|
|
665
|
+
if not etag:
|
|
482
666
|
return True # No validation if no checksum
|
|
483
667
|
|
|
484
668
|
try:
|
|
485
|
-
|
|
486
|
-
|
|
669
|
+
resolved_path = self._resolve_rpath(rpath, rtype)
|
|
670
|
+
current_hash = calculate_file_hash(resolved_path, self.config.hash_algorithm)
|
|
671
|
+
|
|
672
|
+
return current_hash == etag
|
|
487
673
|
except Exception as e:
|
|
488
|
-
logger.error(f"Failed to validate resource: {
|
|
674
|
+
logger.error(f"Failed to validate resource: {rname}", exc_info=e)
|
|
489
675
|
return False
|
|
490
676
|
|
|
491
677
|
# def export_metadata(self, path: Path) -> None:
|
|
@@ -521,18 +707,20 @@ class BiocFileCache:
|
|
|
521
707
|
# session.merge(resource)
|
|
522
708
|
# session.commit()
|
|
523
709
|
|
|
524
|
-
def verify_cache(self) ->
|
|
710
|
+
def verify_cache(self) -> tuple[int, int]:
|
|
525
711
|
"""Verify integrity of all cached resources.
|
|
526
712
|
|
|
527
713
|
Returns:
|
|
528
714
|
Tuple of (valid_count, invalid_count).
|
|
529
715
|
"""
|
|
530
716
|
valid = invalid = 0
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
717
|
+
with self.get_session() as session:
|
|
718
|
+
for resource in session.query(Resource).all():
|
|
719
|
+
if self.validate_resource(resource):
|
|
720
|
+
valid += 1
|
|
721
|
+
else:
|
|
722
|
+
invalid += 1
|
|
723
|
+
|
|
536
724
|
return valid, invalid
|
|
537
725
|
|
|
538
726
|
def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame:
|
|
@@ -549,17 +737,21 @@ class BiocFileCache:
|
|
|
549
737
|
Whether to require exact match.
|
|
550
738
|
|
|
551
739
|
Returns:
|
|
552
|
-
|
|
740
|
+
BiocFrame of matching resources.
|
|
553
741
|
"""
|
|
742
|
+
if field not in Resource.__table__.columns:
|
|
743
|
+
raise ValueError(f"Invalid search field: '{field}'")
|
|
744
|
+
|
|
745
|
+
column = getattr(Resource, field)
|
|
554
746
|
with self.get_session() as session:
|
|
555
747
|
if exact:
|
|
556
|
-
resources = session.query(Resource).filter(
|
|
748
|
+
resources = session.query(Resource).filter(column == query).all()
|
|
557
749
|
else:
|
|
558
|
-
resources = session.query(Resource).filter(
|
|
750
|
+
resources = session.query(Resource).filter(column.ilike(f"%{query}%")).all()
|
|
559
751
|
|
|
560
752
|
return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
|
|
561
753
|
|
|
562
|
-
def get_stats(self) ->
|
|
754
|
+
def get_stats(self) -> dict[str, Any]:
|
|
563
755
|
"""Get statistics about the cache."""
|
|
564
756
|
with self.get_session() as session:
|
|
565
757
|
total = session.query(Resource).count()
|
|
@@ -567,7 +759,7 @@ class BiocFileCache:
|
|
|
567
759
|
session.query(Resource)
|
|
568
760
|
.filter(
|
|
569
761
|
Resource.expires.isnot(None), # Only check resources with expiration
|
|
570
|
-
Resource.expires <
|
|
762
|
+
Resource.expires < _now(),
|
|
571
763
|
)
|
|
572
764
|
.count()
|
|
573
765
|
)
|
|
@@ -602,7 +794,7 @@ class BiocFileCache:
|
|
|
602
794
|
|
|
603
795
|
for resource in resources:
|
|
604
796
|
try:
|
|
605
|
-
|
|
797
|
+
self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
|
|
606
798
|
except Exception as e:
|
|
607
799
|
if not force:
|
|
608
800
|
session.rollback()
|
|
@@ -622,7 +814,7 @@ class BiocFileCache:
|
|
|
622
814
|
except Exception as e:
|
|
623
815
|
logger.warning(f"Failed to remove {file}: {e}")
|
|
624
816
|
|
|
625
|
-
self._last_cleanup =
|
|
817
|
+
self._last_cleanup = _now()
|
|
626
818
|
return True
|
|
627
819
|
|
|
628
820
|
except Exception as e:
|
pybiocfilecache/config.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
from dataclasses import dataclass
|
|
2
2
|
from datetime import timedelta
|
|
3
3
|
from pathlib import Path
|
|
4
|
-
from typing import Optional
|
|
5
4
|
|
|
6
5
|
__author__ = "Jayaram Kancherla"
|
|
7
6
|
__copyright__ = "Jayaram Kancherla"
|
|
@@ -28,6 +27,6 @@ class CacheConfig:
|
|
|
28
27
|
"""
|
|
29
28
|
|
|
30
29
|
cache_dir: Path
|
|
31
|
-
cleanup_interval:
|
|
30
|
+
cleanup_interval: timedelta | None = None # timedelta(days=30)
|
|
32
31
|
rname_pattern: str = r"^[a-zA-Z0-9_-]+$"
|
|
33
32
|
hash_algorithm: str = "md5"
|
pybiocfilecache/models.py
CHANGED
|
@@ -62,9 +62,10 @@ class Resource(Base):
|
|
|
62
62
|
"""
|
|
63
63
|
|
|
64
64
|
__tablename__ = "resource"
|
|
65
|
+
__table_args__ = {"sqlite_autoincrement": True}
|
|
65
66
|
|
|
66
67
|
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
|
|
67
|
-
rid = Column(Text())
|
|
68
|
+
rid = Column(Text(), unique=True)
|
|
68
69
|
rname = Column(Text())
|
|
69
70
|
create_time = Column(DateTime, server_default=func.now())
|
|
70
71
|
access_time = Column(DateTime, server_default=func.now())
|
pybiocfilecache/py.typed
ADDED
|
File without changes
|
pybiocfilecache/utils.py
CHANGED
|
@@ -7,7 +7,8 @@ import uuid
|
|
|
7
7
|
import zlib
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
from shutil import copy2, move
|
|
10
|
-
from typing import
|
|
10
|
+
from typing import Literal
|
|
11
|
+
from urllib.parse import urlparse
|
|
11
12
|
|
|
12
13
|
__author__ = "Jayaram Kancherla"
|
|
13
14
|
__copyright__ = "Jayaram Kancherla"
|
|
@@ -26,10 +27,9 @@ def generate_uuid() -> str:
|
|
|
26
27
|
return uuid.uuid4().hex
|
|
27
28
|
|
|
28
29
|
|
|
29
|
-
def generate_id(
|
|
30
|
-
"""Generate unique identifier."""
|
|
31
|
-
|
|
32
|
-
return "BFC" + str(size)
|
|
30
|
+
def generate_id(row_id: int) -> str:
|
|
31
|
+
"""Generate unique resource identifier from database row id."""
|
|
32
|
+
return f"BFC{row_id}"
|
|
33
33
|
|
|
34
34
|
|
|
35
35
|
def validate_rname(rname: str, pattern: str) -> bool:
|
|
@@ -43,6 +43,7 @@ def calculate_file_hash(path: Path, algorithm: str = "md5") -> str:
|
|
|
43
43
|
with open(path, "rb") as f:
|
|
44
44
|
for chunk in iter(lambda: f.read(4096), b""):
|
|
45
45
|
hasher.update(chunk)
|
|
46
|
+
|
|
46
47
|
return hasher.hexdigest()
|
|
47
48
|
|
|
48
49
|
|
|
@@ -88,7 +89,13 @@ def copy_or_move(
|
|
|
88
89
|
raise Exception(f"Failed to store resource '{rname}' from '{source}' to '{target}'") from e
|
|
89
90
|
|
|
90
91
|
|
|
91
|
-
def download_web_file(url: str, filename: str, download: bool):
|
|
92
|
+
def download_web_file(url: str, filename: str | None = None, download: bool = True) -> Path:
|
|
93
|
+
"""Download a web resource into a temporary directory."""
|
|
94
|
+
|
|
95
|
+
if not filename:
|
|
96
|
+
parsed_name = Path(urlparse(str(url)).path).name
|
|
97
|
+
filename = parsed_name or "download"
|
|
98
|
+
|
|
92
99
|
tmp_dir = create_tmp_dir()
|
|
93
100
|
outpath = tmp_dir / filename
|
|
94
101
|
if download:
|
|
@@ -99,7 +106,7 @@ def download_web_file(url: str, filename: str, download: bool):
|
|
|
99
106
|
return outpath
|
|
100
107
|
|
|
101
108
|
|
|
102
|
-
def convert_to_columnar(list_of_dicts:
|
|
109
|
+
def convert_to_columnar(list_of_dicts: list[dict]):
|
|
103
110
|
if not list_of_dicts:
|
|
104
111
|
return {}
|
|
105
112
|
|
|
@@ -109,4 +116,5 @@ def convert_to_columnar(list_of_dicts: List[dict]):
|
|
|
109
116
|
for row in list_of_dicts:
|
|
110
117
|
for col in column_names:
|
|
111
118
|
result[col].append(row.get(col))
|
|
119
|
+
|
|
112
120
|
return result
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pybiocfilecache
|
|
3
|
+
Version: 0.8.0
|
|
4
|
+
Summary: File based cache for resources and metadata
|
|
5
|
+
Project-URL: Homepage, https://github.com/BiocPy/pybiocfilecache
|
|
6
|
+
Project-URL: Documentation, https://biocpy.github.io/pybiocfilecache
|
|
7
|
+
Project-URL: Repository, https://github.com/BiocPy/pybiocfilecache
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/BiocPy/pybiocfilecache/issues
|
|
9
|
+
Author-email: Jayaram Kancherla <jayaram.kancherla@gmail.com>
|
|
10
|
+
License: The MIT License (MIT)
|
|
11
|
+
|
|
12
|
+
Copyright (c) 2021 Genentech, Inc.
|
|
13
|
+
|
|
14
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
15
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
16
|
+
in the Software without restriction, including without limitation the rights
|
|
17
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
18
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
19
|
+
furnished to do so, subject to the following conditions:
|
|
20
|
+
|
|
21
|
+
The above copyright notice and this permission notice shall be included in all
|
|
22
|
+
copies or substantial portions of the Software.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
25
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
26
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
27
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
28
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
|
+
SOFTWARE.
|
|
31
|
+
License-File: AUTHORS.md
|
|
32
|
+
License-File: LICENSE.txt
|
|
33
|
+
Keywords: biocfilecache,cache,file-cache,resource-management,sqlite
|
|
34
|
+
Classifier: Development Status :: 4 - Beta
|
|
35
|
+
Classifier: Intended Audience :: Developers
|
|
36
|
+
Classifier: Intended Audience :: Science/Research
|
|
37
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
38
|
+
Classifier: Operating System :: OS Independent
|
|
39
|
+
Classifier: Programming Language :: Python :: 3
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
45
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
46
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
47
|
+
Requires-Python: >=3.9
|
|
48
|
+
Requires-Dist: biocframe
|
|
49
|
+
Requires-Dist: sqlalchemy
|
|
50
|
+
Provides-Extra: testing
|
|
51
|
+
Requires-Dist: pytest; extra == 'testing'
|
|
52
|
+
Requires-Dist: pytest-cov; extra == 'testing'
|
|
53
|
+
Requires-Dist: setuptools; extra == 'testing'
|
|
54
|
+
Description-Content-Type: text/markdown
|
|
55
|
+
|
|
56
|
+
```{include} ../README.md
|
|
57
|
+
:relative-docs: docs/
|
|
58
|
+
:relative-images:
|
|
59
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
|
|
2
|
+
pybiocfilecache/cache.py,sha256=-5R14I5np3WRKLpGpxvMhuLez1bII_NF6WXurkMc2gk,30906
|
|
3
|
+
pybiocfilecache/config.py,sha256=4tm0aAiNdxOn3rqJNHHgAWRNV8c8iDB1FLMnK9tuA0c,772
|
|
4
|
+
pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
|
|
5
|
+
pybiocfilecache/models.py,sha256=6CFAmSLDhIBjBGU2leV6B4MxEZQQnJE0xrF55CRT6mw,2582
|
|
6
|
+
pybiocfilecache/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
pybiocfilecache/utils.py,sha256=HzONrEmukpHVJkXKMrvVVV2DSwn2vynK_o72dggKtCE,3247
|
|
8
|
+
pybiocfilecache-0.8.0.dist-info/METADATA,sha256=6ur2OEuMM_psEfBvB-QIksO_WYXlK7PEWV-8cTMR9S4,2837
|
|
9
|
+
pybiocfilecache-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
pybiocfilecache-0.8.0.dist-info/licenses/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
|
|
11
|
+
pybiocfilecache-0.8.0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
|
|
12
|
+
pybiocfilecache-0.8.0.dist-info/RECORD,,
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: pyBiocFileCache
|
|
3
|
-
Version: 0.7.0
|
|
4
|
-
Summary: File based cache for resources and metadata
|
|
5
|
-
Home-page: https://github.com/biocpy/pyBiocFileCache
|
|
6
|
-
Author: jkanche
|
|
7
|
-
Author-email: jayaram.kancherla@gmail.com
|
|
8
|
-
License: MIT
|
|
9
|
-
Project-URL: Documentation, https://github.com/biocpy/pyBiocFileCache
|
|
10
|
-
Platform: any
|
|
11
|
-
Classifier: Development Status :: 4 - Beta
|
|
12
|
-
Classifier: Programming Language :: Python
|
|
13
|
-
Requires-Python: >=3.9
|
|
14
|
-
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
15
|
-
License-File: LICENSE.txt
|
|
16
|
-
License-File: AUTHORS.md
|
|
17
|
-
Requires-Dist: importlib-metadata; python_version < "3.8"
|
|
18
|
-
Requires-Dist: sqlalchemy
|
|
19
|
-
Requires-Dist: biocframe
|
|
20
|
-
Provides-Extra: testing
|
|
21
|
-
Requires-Dist: setuptools; extra == "testing"
|
|
22
|
-
Requires-Dist: pytest; extra == "testing"
|
|
23
|
-
Requires-Dist: pytest-cov; extra == "testing"
|
|
24
|
-
Dynamic: license-file
|
|
25
|
-
|
|
26
|
-
[](https://pyscaffold.org/)
|
|
27
|
-
[](https://pypi.org/project/pyBiocFileCache/)
|
|
28
|
-

|
|
29
|
-
|
|
30
|
-
# pyBiocFileCache
|
|
31
|
-
|
|
32
|
-
`pyBiocFileCache` is a Python package that provides a robust file caching system with resource validation, cache size management, file compression, and resource tagging. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache).
|
|
33
|
-
|
|
34
|
-
## Installation
|
|
35
|
-
|
|
36
|
-
Install from [PyPI](https://pypi.org/project/pyBiocFileCache/),
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
pip install pybiocfilecache
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## Quick Start
|
|
43
|
-
|
|
44
|
-
```python
|
|
45
|
-
from pybiocfilecache import BiocFileCache
|
|
46
|
-
|
|
47
|
-
# Initialize cache
|
|
48
|
-
cache = BiocFileCache("path/to/cache/directory")
|
|
49
|
-
|
|
50
|
-
# Add a file to cache
|
|
51
|
-
resource = cache.add("myfile", "path/to/file.txt")
|
|
52
|
-
|
|
53
|
-
# Retrieve a file from cache
|
|
54
|
-
resource = cache.get("myfile")
|
|
55
|
-
|
|
56
|
-
# Use the cached file
|
|
57
|
-
print(resource["rpath"]) # Path to cached file
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
## Advanced Usage
|
|
61
|
-
|
|
62
|
-
### Configuration
|
|
63
|
-
|
|
64
|
-
```python
|
|
65
|
-
from pybiocfilecache import BiocFileCache, CacheConfig
|
|
66
|
-
from datetime import timedelta
|
|
67
|
-
from pathlib import Path
|
|
68
|
-
|
|
69
|
-
# Create custom configuration
|
|
70
|
-
config = CacheConfig(
|
|
71
|
-
cache_dir=Path("cache_directory"),
|
|
72
|
-
cleanup_interval=timedelta(days=7),
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
# Initialize cache with configuration
|
|
76
|
-
cache = BiocFileCache(config=config)
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
### Resource Management
|
|
80
|
-
|
|
81
|
-
```python
|
|
82
|
-
# Add file with tags and expiration
|
|
83
|
-
from datetime import datetime, timedelta
|
|
84
|
-
|
|
85
|
-
resource = cache.add(
|
|
86
|
-
"myfile",
|
|
87
|
-
"path/to/file.txt",
|
|
88
|
-
tags=["data", "raw"],
|
|
89
|
-
expires=datetime.now() + timedelta(days=30)
|
|
90
|
-
)
|
|
91
|
-
|
|
92
|
-
# List resources by tag
|
|
93
|
-
resources = cache.list_resources(tag="data")
|
|
94
|
-
|
|
95
|
-
# Search resources
|
|
96
|
-
results = cache.search("myfile", field="rname")
|
|
97
|
-
|
|
98
|
-
# Update resource
|
|
99
|
-
cache.update("myfile", "path/to/new_file.txt")
|
|
100
|
-
|
|
101
|
-
# Remove resource
|
|
102
|
-
cache.remove("myfile")
|
|
103
|
-
```
|
|
104
|
-
|
|
105
|
-
### Cache Statistics and Maintenance
|
|
106
|
-
|
|
107
|
-
```python
|
|
108
|
-
# Get cache statistics
|
|
109
|
-
stats = cache.get_stats()
|
|
110
|
-
print(stats)
|
|
111
|
-
|
|
112
|
-
# Clean up expired resources
|
|
113
|
-
removed_count = cache.cleanup()
|
|
114
|
-
|
|
115
|
-
# Purge entire cache
|
|
116
|
-
cache.purge()
|
|
117
|
-
```
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
|
|
2
|
-
pybiocfilecache/cache.py,sha256=VELZ8Ao_9clIUvKXjkCSFsXwf8KK2s4yLOJWT4xxneo,23666
|
|
3
|
-
pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
|
|
4
|
-
pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
|
|
5
|
-
pybiocfilecache/models.py,sha256=ahnGpEhoZzXzvzb9lphs45uU2wts-_q26LOA_P3URKo,2517
|
|
6
|
-
pybiocfilecache/utils.py,sha256=M59NG_oMVvVw03t1hDNaaKtcBZWY4U0KSfpQx_L5U1Y,2981
|
|
7
|
-
pybiocfilecache-0.7.0.dist-info/licenses/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
|
|
8
|
-
pybiocfilecache-0.7.0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
|
|
9
|
-
pybiocfilecache-0.7.0.dist-info/METADATA,sha256=4qvcDLIDVooC3kNk-38vk2ETPgRC9XoDeSvqHns0gR4,3015
|
|
10
|
-
pybiocfilecache-0.7.0.dist-info/WHEEL,sha256=1tXe9gY0PYatrMPMDd6jXqjfpz_B-Wqm32CPfRC58XU,91
|
|
11
|
-
pybiocfilecache-0.7.0.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
|
|
12
|
-
pybiocfilecache-0.7.0.dist-info/RECORD,,
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
pybiocfilecache
|
|
File without changes
|
|
File without changes
|