pyBiocFileCache 0.7.0__py3-none-any.whl → 0.8.0.dev0__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 CHANGED
@@ -1,6 +1,7 @@
1
1
  import logging
2
+ import shutil
2
3
  from contextlib import contextmanager
3
- from datetime import datetime
4
+ from datetime import datetime, timezone
4
5
  from pathlib import Path
5
6
  from time import sleep, time
6
7
  from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
@@ -30,6 +31,19 @@ __license__ = "MIT"
30
31
  logger = logging.getLogger(__name__)
31
32
 
32
33
 
34
+ def _now() -> datetime:
35
+ """Return current UTC time as a naive datetime matching SQLite CURRENT_TIMESTAMP."""
36
+ return datetime.now(timezone.utc).replace(tzinfo=None)
37
+
38
+
39
+ def _normalize_datetime(dt: Optional[datetime]) -> Optional[datetime]:
40
+ """Normalize an optional datetime to naive UTC."""
41
+ if dt is not None and dt.tzinfo is not None:
42
+ return dt.astimezone(timezone.utc).replace(tzinfo=None)
43
+
44
+ return dt
45
+
46
+
33
47
  class BiocFileCache:
34
48
  """Enhanced file caching module.
35
49
 
@@ -63,7 +77,7 @@ class BiocFileCache:
63
77
  if db_schema_version != SCHEMA_VERSION:
64
78
  raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
65
79
 
66
- self._last_cleanup = datetime.now()
80
+ self._last_cleanup = _now()
67
81
 
68
82
  def _setup_cache_dir(self) -> bool:
69
83
  if not self.config.cache_dir.exists():
@@ -106,6 +120,14 @@ class BiocFileCache:
106
120
 
107
121
  return SCHEMA_VERSION
108
122
 
123
+ def _resolve_rpath(self, rpath: str, rtype: Optional[str]) -> Path:
124
+ """Resolve a stored resource path against cache_dir when relative."""
125
+ path = Path(rpath)
126
+ if rtype in ("relative", "web") and not path.is_absolute():
127
+ return self.config.cache_dir / path
128
+
129
+ return path
130
+
109
131
  def _get_detached_resource(self, session: Session, obj: Union[Resource, Metadata]) -> Optional[dict]:
110
132
  """Get a detached copy of a resource."""
111
133
  if obj is None:
@@ -114,9 +136,8 @@ class BiocFileCache:
114
136
  session.expunge(obj)
115
137
  obj_dict = obj.to_dict()
116
138
 
117
- if isinstance(obj, Resource):
118
- if obj_dict["rtype"] == "relative":
119
- obj_dict["rpath"] = f"{self.config.cache_dir}/{obj_dict['rpath']}"
139
+ if isinstance(obj, Resource) and obj_dict["rtype"] in ("relative", "web"):
140
+ obj_dict["rpath"] = str(self._resolve_rpath(obj_dict["rpath"], obj_dict["rtype"]))
120
141
 
121
142
  return obj_dict
122
143
 
@@ -161,7 +182,7 @@ class BiocFileCache:
161
182
  if self.config.cleanup_interval is None:
162
183
  return False
163
184
 
164
- return datetime.now() - self._last_cleanup > self.config.cleanup_interval
185
+ return _now() - self._last_cleanup > self.config.cleanup_interval
165
186
 
166
187
  def cleanup(self) -> int:
167
188
  """Remove expired resources from the cache.
@@ -170,27 +191,25 @@ class BiocFileCache:
170
191
  Number of resources removed.
171
192
 
172
193
  Note:
173
- - If `cleanup_interval` is None, this method will still run if called explicitly.
194
+ - Runs whenever called explicitly, even if `cleanup_interval` is None.
174
195
  - Only removes resources with non-None expiration dates.
175
196
  """
176
- if not any([self.config.cleanup_interval, self._should_cleanup()]):
177
- return 0 # Early return if automatic cleanup is disabled
178
-
179
197
  removed = 0
198
+ now = _now()
180
199
  with self.get_session() as session:
181
200
  # Only query resources that have expiration dates
182
201
  expired = (
183
202
  session.query(Resource)
184
203
  .filter(
185
204
  Resource.expires.isnot(None), # Only check resources with expiration
186
- Resource.expires < datetime.now(),
205
+ Resource.expires < now,
187
206
  )
188
207
  .all()
189
208
  )
190
209
 
191
210
  for resource in expired:
192
211
  try:
193
- Path(resource.rpath).unlink(missing_ok=True)
212
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
194
213
  session.delete(resource)
195
214
  removed += 1
196
215
  except Exception as e:
@@ -198,15 +217,21 @@ class BiocFileCache:
198
217
 
199
218
  session.commit()
200
219
 
201
- self._last_cleanup = datetime.now()
220
+ self._last_cleanup = now
202
221
  return removed
203
222
 
204
223
  ###############################
205
224
  ######>> get resources <<######
206
225
  ###############################
207
226
 
208
- def get(self, rname: str = None, rid: str = None) -> Optional[dict]:
209
- """Get resource by name from cache.
227
+ def get(
228
+ self,
229
+ rname: Optional[str] = None,
230
+ rid: Optional[str] = None,
231
+ wait: bool = True,
232
+ timeout: float = 30,
233
+ ) -> Optional[dict]:
234
+ """Get resource by name or id from cache.
210
235
 
211
236
  Args:
212
237
  rname:
@@ -215,32 +240,110 @@ class BiocFileCache:
215
240
  rid:
216
241
  Resource id to search by.
217
242
 
243
+ wait:
244
+ Whether to wait for the cached file to exist on disk.
245
+ If False, returns the registered record immediately even if
246
+ the file is missing. Defaults to True.
247
+
248
+ timeout:
249
+ Maximum seconds to wait when `wait=True`. Defaults to 30.
250
+
218
251
  """
219
252
  if rname is None and rid is None:
220
253
  raise ValueError("either 'rname' or 'rid' must be provided.")
221
254
 
222
255
  with self.get_session() as session:
223
- if rname is not None:
224
- resource = session.query(Resource).filter(Resource.rname == rname).first()
225
- elif rid is not None:
256
+ if rid is not None:
226
257
  resource = session.query(Resource).filter(Resource.rid == rid).first()
258
+ else:
259
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
227
260
 
228
261
  if resource is not None:
229
- # Check if path exists with timeout
230
- start = time()
231
- timeout = 30
232
- while not Path(str(self.config.cache_dir / resource.rpath)).exists():
233
- if time() - start >= timeout:
234
- raise TimeoutError(f"For resource: '{rname}' the rpath does not exist after {timeout} seconds.")
235
- sleep(0.1)
262
+ if wait:
263
+ resolved_path = self._resolve_rpath(resource.rpath, resource.rtype)
264
+ start = time()
265
+ while not resolved_path.exists():
266
+ if time() - start >= timeout:
267
+ identifier = rid if rid is not None else rname
268
+ raise TimeoutError(
269
+ f"For resource: '{identifier}' the rpath does not exist after {timeout} seconds."
270
+ )
271
+ sleep(0.1)
236
272
 
237
273
  # Update access time
238
- resource.access_time = datetime.now()
274
+ resource.access_time = _now()
239
275
  session.commit()
240
276
  return self._get_detached_resource(session, resource)
241
277
 
242
278
  return None
243
279
 
280
+ def _add_to_session(
281
+ self,
282
+ session: Session,
283
+ rname: str,
284
+ fpath: Union[str, Path],
285
+ rtype: Literal["local", "web", "relative"] = "relative",
286
+ action: Literal["copy", "move", "asis"] = "copy",
287
+ expires: Optional[datetime] = None,
288
+ download: bool = True,
289
+ ext: bool = True,
290
+ ) -> Tuple[Resource, Optional[Path]]:
291
+ """Insert a resource record and store its file within an active session."""
292
+ if session.query(Resource).filter(Resource.rname == rname).first() is not None:
293
+ raise FileExistsError(f"Resource '{rname}' already exists")
294
+
295
+ fpath_val = Path(fpath) if rtype != "web" else fpath
296
+ tmp_dir: Optional[Path] = None
297
+
298
+ if rtype == "web":
299
+ outpath = download_web_file(str(fpath_val), None, download)
300
+ tmp_dir = outpath.parent
301
+ action = "copy"
302
+ else:
303
+ outpath = Path(fpath_val)
304
+
305
+ if action == "asis":
306
+ if rtype != "local":
307
+ logger.warning("If action='asis', rtype must be 'local'.")
308
+ rtype = "local"
309
+ elif rtype == "local":
310
+ rtype = "relative"
311
+
312
+ uuid_str = generate_uuid()
313
+ rpath = f"{uuid_str}_{outpath.name if ext else outpath.stem}" if action != "asis" else str(fpath_val)
314
+
315
+ resource = Resource(
316
+ rid=None,
317
+ rname=rname,
318
+ rpath=str(rpath),
319
+ rtype=rtype,
320
+ fpath=str(fpath_val),
321
+ expires=_normalize_datetime(expires),
322
+ )
323
+
324
+ copied_target: Optional[Path] = None
325
+ try:
326
+ session.add(resource)
327
+ session.flush()
328
+ resource.rid = generate_id(resource.id)
329
+
330
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
331
+ copy_or_move(outpath, target_path, rname, action, False)
332
+ if action != "asis":
333
+ copied_target = target_path
334
+
335
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
336
+
337
+ return resource, copied_target
338
+ except Exception:
339
+ if copied_target is not None and copied_target.exists():
340
+ copied_target.unlink(missing_ok=True)
341
+
342
+ raise
343
+ finally:
344
+ if tmp_dir is not None:
345
+ shutil.rmtree(tmp_dir, ignore_errors=True)
346
+
244
347
  def add(
245
348
  self,
246
349
  rname: str,
@@ -263,7 +366,7 @@ class BiocFileCache:
263
366
  rtype:
264
367
  Type of resource.
265
368
  One of ``local``, ``web``, or ``relative``.
266
- Defaults to ``local``.
369
+ Defaults to ``relative``.
267
370
 
268
371
  action:
269
372
  How to handle the file ("copy", "move", or "asis").
@@ -284,54 +387,26 @@ class BiocFileCache:
284
387
  Returns:
285
388
  The `Resource` object added to the cache as dictionary.
286
389
  """
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
390
  with self.get_session() as session:
320
- session.add(resource)
321
- session.commit()
322
-
323
391
  try:
324
- copy_or_move(outpath, self.config.cache_dir / rpath, rname, action, False)
325
-
326
- # Calculate and store checksum
327
- resource.etag = calculate_file_hash(self.config.cache_dir / rpath, self.config.hash_algorithm)
392
+ resource, _ = self._add_to_session(
393
+ session=session,
394
+ rname=rname,
395
+ fpath=fpath,
396
+ rtype=rtype,
397
+ action=action,
398
+ expires=expires,
399
+ download=download,
400
+ ext=ext,
401
+ )
328
402
  session.commit()
329
- result = self._get_detached_resource(session, resource)
330
- return result
331
-
403
+
404
+ return self._get_detached_resource(session, resource)
405
+ except FileExistsError:
406
+ session.rollback()
407
+ raise
332
408
  except Exception as e:
333
- session.delete(resource)
334
- session.commit()
409
+ session.rollback()
335
410
  raise Exception("Failed to add resource") from e
336
411
 
337
412
  def add_batch(self, resources: List[Dict[str, Any]]) -> BiocFrame:
@@ -341,23 +416,36 @@ class BiocFileCache:
341
416
  resources:
342
417
  List of resources to add.
343
418
  """
344
- results = []
419
+ added_resources: List[Resource] = []
420
+ copied_targets: List[Path] = []
345
421
  with self.get_session() as session:
346
- for resource_info in resources:
347
- try:
348
- resource = self.add(**resource_info)
349
- results.append(resource)
350
- except Exception as e:
351
- logger.error(f"Failed to add resource: {resource_info.get('rname')}", exc_info=e)
352
- session.rollback()
353
- raise
354
- return results
422
+ try:
423
+ for resource_info in resources:
424
+ resource, copied_target = self._add_to_session(session=session, **resource_info)
425
+ added_resources.append(resource)
426
+ if copied_target is not None:
427
+ copied_targets.append(copied_target)
428
+
429
+ session.commit()
430
+
431
+ return BiocFrame(
432
+ convert_to_columnar([self._get_detached_resource(session, r) for r in added_resources])
433
+ )
434
+ except Exception as e:
435
+ logger.error("Failed to add batch of resources", exc_info=e)
436
+ session.rollback()
437
+
438
+ for target in copied_targets:
439
+ target.unlink(missing_ok=True)
440
+
441
+ raise
355
442
 
356
443
  def update(
357
444
  self,
358
- rname: str,
359
- fpath: Union[str, Path],
445
+ rname: Optional[str] = None,
446
+ fpath: Union[str, Path] = None,
360
447
  action: Literal["copy", "move", "asis"] = "copy",
448
+ rid: Optional[str] = None,
361
449
  ) -> dict:
362
450
  """Update an existing resource.
363
451
 
@@ -372,36 +460,62 @@ class BiocFileCache:
372
460
  Either ``copy``, ``move`` or ``asis``.
373
461
  Defaults to ``copy``.
374
462
 
463
+ rid:
464
+ Optional resource id to identify the resource.
465
+
375
466
  Returns:
376
467
  Updated `Resource` object as dictionary.
377
468
 
378
469
  """
470
+ if rname is None and rid is None:
471
+ raise ValueError("either 'rname' or 'rid' must be provided.")
472
+
473
+ if fpath is None:
474
+ raise ValueError("'fpath' must be provided.")
475
+
379
476
  fpath = Path(fpath)
380
477
  if not fpath.exists():
381
478
  raise FileNotFoundError(f"File '{fpath}' does not exist")
382
479
 
383
480
  with self.get_session() as session:
384
- resource = session.query(Resource).filter(Resource.rname == rname).first()
481
+ if rid is not None:
482
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
483
+ else:
484
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
385
485
 
386
486
  if resource is None:
487
+ if rname is None:
488
+ raise KeyError(f"Resource with rid '{rid}' not found")
387
489
  return self.add(rname=rname, fpath=fpath, action=action)
388
490
 
389
- old_path = Path(resource.rpath)
390
491
  try:
391
- copy_or_move(fpath, old_path, rname, action, False)
492
+ if action == "asis":
493
+ resource.rpath = str(fpath)
494
+ resource.rtype = "local"
495
+ target_path = fpath
496
+ else:
497
+ if resource.rtype == "local":
498
+ resource.rtype = "relative"
499
+ resource.rpath = f"{generate_uuid()}_{fpath.name}"
500
+
501
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
502
+ copy_or_move(fpath, target_path, resource.rname, action, False)
392
503
 
393
- resource.last_modified_time = datetime.now()
394
- resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm)
504
+ resource.fpath = str(fpath)
505
+ resource.last_modified_time = _now()
506
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
395
507
 
396
508
  session.commit()
509
+
397
510
  return self._get_detached_resource(session, resource)
398
511
 
399
512
  except Exception as e:
400
513
  session.rollback()
514
+
401
515
  raise Exception("Failed to update resource") from e
402
516
 
403
- def remove(self, rname: str) -> None:
404
- """Remove a resource from cache by name.
517
+ def remove(self, rname: Optional[str] = None, rid: Optional[str] = None) -> None:
518
+ """Remove a resource from cache by name or id.
405
519
 
406
520
  Removes both the cached file and its database entry.
407
521
 
@@ -409,16 +523,25 @@ class BiocFileCache:
409
523
  rname:
410
524
  Name to identify the resource in cache.
411
525
 
526
+ rid:
527
+ Resource id to identify the resource in cache.
528
+
412
529
  Raises:
413
530
  Exception: If resource removal fails
414
531
  """
532
+ if rname is None and rid is None:
533
+ raise ValueError("either 'rname' or 'rid' must be provided.")
534
+
415
535
  with self.get_session() as session:
416
- resource = session.query(Resource).filter(Resource.rname == rname).first()
536
+ if rid is not None:
537
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
538
+ else:
539
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
417
540
 
418
541
  if resource is not None:
419
542
  try:
420
543
  # Try to remove the file first
421
- rpath = Path(resource.rpath)
544
+ rpath = self._resolve_rpath(resource.rpath, resource.rtype)
422
545
  if rpath.exists():
423
546
  rpath.unlink()
424
547
 
@@ -428,7 +551,8 @@ class BiocFileCache:
428
551
 
429
552
  except Exception as e:
430
553
  session.rollback()
431
- raise Exception(f"Failed to remove resource '{rname}'") from e
554
+ identifier = rid if rid is not None else rname
555
+ raise Exception(f"Failed to remove resource '{identifier}'") from e
432
556
 
433
557
  def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> BiocFrame:
434
558
  """List resources in the cache with optional filtering.
@@ -454,38 +578,52 @@ class BiocFileCache:
454
578
  if rtype:
455
579
  query = query.filter(Resource.rtype == rtype)
456
580
  if expired is not None:
581
+ now = _now()
457
582
  if expired:
458
583
  query = query.filter(
459
584
  Resource.expires.isnot(None), # Only check resources with expiration
460
- Resource.expires < datetime.now(),
585
+ Resource.expires < now,
461
586
  )
462
587
  else:
463
588
  query = query.filter(
464
589
  (Resource.expires.is_(None)) # Never expires
465
- | (Resource.expires > datetime.now()) # Not yet expired
590
+ | (Resource.expires > now) # Not yet expired
466
591
  )
467
592
 
468
593
  resources = query.all()
469
594
  return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
470
595
 
471
- def validate_resource(self, resource: Resource) -> bool:
596
+ def validate_resource(self, resource: Union[Resource, dict]) -> bool:
472
597
  """Validate resource integrity.
473
598
 
474
599
  Args:
475
600
  resource:
476
- Resource to validate.
601
+ Resource ORM object or dictionary to validate.
477
602
 
478
603
  Returns:
479
604
  True if resource is valid, False otherwise.
480
605
  """
481
- if not resource.etag:
606
+ if isinstance(resource, dict):
607
+ etag = resource.get("etag")
608
+ rpath = resource.get("rpath")
609
+ rtype = resource.get("rtype")
610
+ rname = resource.get("rname")
611
+ else:
612
+ etag = resource.etag
613
+ rpath = resource.rpath
614
+ rtype = resource.rtype
615
+ rname = resource.rname
616
+
617
+ if not etag:
482
618
  return True # No validation if no checksum
483
619
 
484
620
  try:
485
- current_hash = calculate_file_hash(Path(resource.rpath), self.config.hash_algorithm)
486
- return current_hash == resource.etag
621
+ resolved_path = self._resolve_rpath(rpath, rtype)
622
+ current_hash = calculate_file_hash(resolved_path, self.config.hash_algorithm)
623
+
624
+ return current_hash == etag
487
625
  except Exception as e:
488
- logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e)
626
+ logger.error(f"Failed to validate resource: {rname}", exc_info=e)
489
627
  return False
490
628
 
491
629
  # def export_metadata(self, path: Path) -> None:
@@ -528,11 +666,13 @@ class BiocFileCache:
528
666
  Tuple of (valid_count, invalid_count).
529
667
  """
530
668
  valid = invalid = 0
531
- for resource in self.list_resources():
532
- if self.validate_resource(resource):
533
- valid += 1
534
- else:
535
- invalid += 1
669
+ with self.get_session() as session:
670
+ for resource in session.query(Resource).all():
671
+ if self.validate_resource(resource):
672
+ valid += 1
673
+ else:
674
+ invalid += 1
675
+
536
676
  return valid, invalid
537
677
 
538
678
  def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame:
@@ -549,13 +689,17 @@ class BiocFileCache:
549
689
  Whether to require exact match.
550
690
 
551
691
  Returns:
552
- List of matching resources.
692
+ BiocFrame of matching resources.
553
693
  """
694
+ if field not in Resource.__table__.columns:
695
+ raise ValueError(f"Invalid search field: '{field}'")
696
+
697
+ column = getattr(Resource, field)
554
698
  with self.get_session() as session:
555
699
  if exact:
556
- resources = session.query(Resource).filter(Resource[field] == query).all()
700
+ resources = session.query(Resource).filter(column == query).all()
557
701
  else:
558
- resources = session.query(Resource).filter(Resource[field].ilike(f"%{query}%")).all()
702
+ resources = session.query(Resource).filter(column.ilike(f"%{query}%")).all()
559
703
 
560
704
  return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
561
705
 
@@ -567,7 +711,7 @@ class BiocFileCache:
567
711
  session.query(Resource)
568
712
  .filter(
569
713
  Resource.expires.isnot(None), # Only check resources with expiration
570
- Resource.expires < datetime.now(),
714
+ Resource.expires < _now(),
571
715
  )
572
716
  .count()
573
717
  )
@@ -602,7 +746,7 @@ class BiocFileCache:
602
746
 
603
747
  for resource in resources:
604
748
  try:
605
- Path(resource.rpath).unlink(missing_ok=True)
749
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
606
750
  except Exception as e:
607
751
  if not force:
608
752
  session.rollback()
@@ -622,7 +766,7 @@ class BiocFileCache:
622
766
  except Exception as e:
623
767
  logger.warning(f"Failed to remove {file}: {e}")
624
768
 
625
- self._last_cleanup = datetime.now()
769
+ self._last_cleanup = _now()
626
770
  return True
627
771
 
628
772
  except Exception as e:
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())
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 List, Literal
10
+ from typing import List, Literal, Optional
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(size) -> str:
30
- """Generate unique identifier."""
31
- size += 1
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: Optional[str] = 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:
@@ -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,21 @@
1
+ Metadata-Version: 2.5
2
+ Name: pybiocfilecache
3
+ Version: 0.8.0.dev0
4
+ Summary: File based cache for resources and metadata
5
+ Author-email: Jayaram Kancherla <jayaram.kancherla@gmail.com>
6
+ License-File: AUTHORS.md
7
+ License-File: LICENSE.txt
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: biocframe>=0.7.3
10
+ Requires-Dist: importlib-metadata>=9.0.0; python_full_version < '3.8'
11
+ Requires-Dist: sqlalchemy>=2.0.52
12
+ Provides-Extra: testing
13
+ Requires-Dist: pytest-cov>=7.1.0; extra == 'testing'
14
+ Requires-Dist: pytest>=9.1.1; extra == 'testing'
15
+ Requires-Dist: setuptools>=84.0.0; extra == 'testing'
16
+ Description-Content-Type: text/markdown
17
+
18
+ ```{include} ../README.md
19
+ :relative-docs: docs/
20
+ :relative-images:
21
+ ```
@@ -0,0 +1,12 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=EJ8seT-OeW2uaTr58HK_qyXtfSR6P6sf4zfPrPn6WmY,29136
3
+ pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
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=fzr00U8D3yGp09gYJfhvHoQrt5P5KbVpLNsNkJfB4hY,3282
8
+ pybiocfilecache-0.8.0.dev0.dist-info/METADATA,sha256=HrmOTJC2Ueqi4QPfSqnEZVJ260PWQ8nzL7vNqq7sOD4,681
9
+ pybiocfilecache-0.8.0.dev0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ pybiocfilecache-0.8.0.dev0.dist-info/licenses/AUTHORS.md,sha256=6nnc80t6djIXiPNai5Mumh8ROiq0E19XOlhCGgKc8Uw,71
11
+ pybiocfilecache-0.8.0.dev0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
12
+ pybiocfilecache-0.8.0.dev0.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (77.0.3)
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
-
@@ -0,0 +1,4 @@
1
+ ```{include} ../AUTHORS.md
2
+ :relative-docs: docs/
3
+ :relative-images:
4
+ ```
@@ -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
- [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
27
- [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
28
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
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,5 +0,0 @@
1
- # Contributors
2
-
3
- * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
5
- * Oleksandr Khoroshevskyi <khorosh@virginia.edu>
@@ -1 +0,0 @@
1
- pybiocfilecache