pyBiocFileCache 0.2.2__py3-none-any.whl → 0.3.1__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.
@@ -1,4 +1,4 @@
1
1
  # Contributors
2
2
 
3
3
  * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
4
+ * Max Hargreaves <max_hargreaves@outlook.com>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.2.2
3
+ Version: 0.3.1
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -13,13 +13,17 @@ Classifier: Programming Language :: Python
13
13
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
14
  License-File: LICENSE.txt
15
15
  License-File: AUTHORS.md
16
- Requires-Dist: sqlalchemy (<2.0,>=1.4)
16
+ Requires-Dist: sqlalchemy <2.1,>=2
17
17
  Requires-Dist: importlib-metadata ; python_version < "3.8"
18
18
  Provides-Extra: testing
19
19
  Requires-Dist: setuptools ; extra == 'testing'
20
20
  Requires-Dist: pytest ; extra == 'testing'
21
21
  Requires-Dist: pytest-cov ; extra == 'testing'
22
22
 
23
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
+ [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
25
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
26
+
23
27
  # pyBiocFileCache
24
28
 
25
29
  File system based cache for resources & metadata. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache)
@@ -34,7 +38,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
34
38
  pip install pybiocfilecache
35
39
  ```
36
40
 
37
- #### Initialize a cache directory
41
+ #### Initialize a cache directory
38
42
 
39
43
  ```
40
44
  from pybiocfilecache import BiocFileCache
@@ -0,0 +1,13 @@
1
+ pybiocfilecache/BiocFileCache.py,sha256=8Yau3LfXTo7lW18XTOOQoJ_6VW5-dQQxmSUSEal4v_Q,8589
2
+ pybiocfilecache/__init__.py,sha256=5SUhxaA5370FRyHOs5miL4WXxe2fNODbO_I6VRqDCB0,915
3
+ pybiocfilecache/_exceptions.py,sha256=347Lt1Rrt-TTzP5yEqlRM1QoaPBXB1UnZXv0GfhZmv0,374
4
+ pybiocfilecache/utils.py,sha256=jsaF6B1FViqfiWBJEq4ZCY7eI0bznpcozWkbGbBDH0c,2054
5
+ pybiocfilecache/db/Base.py,sha256=5kIUy1DHqJVKQQwVG017nh-HxCnz1XljiefJaG7c59E,948
6
+ pybiocfilecache/db/__init__.py,sha256=XE1DrTqLmDOM4Y4Qt3fdr6ahir5Vqug5e5v-DQexCDw,102
7
+ pybiocfilecache/db/schema.py,sha256=alr2YCfCmYb7xt8pzXqwpY-eBLNA3oR4nD8ruVzHo6E,1041
8
+ pyBiocFileCache-0.3.1.dist-info/AUTHORS.md,sha256=MMx3vll5oIcyk72Bk3N_ACfHWt5YhAlk2vBjx68m4R8,112
9
+ pyBiocFileCache-0.3.1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
+ pyBiocFileCache-0.3.1.dist-info/METADATA,sha256=B1HXt8rYFB4NO3rtQMaRkzU1Fdiv3HjB3OjV57697ro,2535
11
+ pyBiocFileCache-0.3.1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
12
+ pyBiocFileCache-0.3.1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
+ pyBiocFileCache-0.3.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.40.0)
2
+ Generator: bdist_wheel (0.43.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,36 +1,34 @@
1
- """
2
- Python Implementation of BiocFileCache
3
- """
1
+ """Python Implementation of BiocFileCache."""
4
2
 
5
3
  import os
6
4
  from pathlib import Path
7
5
  from time import sleep, time
8
- from typing import List, Optional, Union
6
+ from typing import List, Literal, Optional, Union
9
7
 
10
8
  from sqlalchemy import func
11
9
  from sqlalchemy.orm import Session
12
10
 
11
+ from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
13
12
  from .db import create_schema
14
13
  from .db.schema import Resource
15
14
  from .utils import copy_or_move, create_tmp_dir, generate_id
16
- from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
17
15
 
18
- __author__ = "jkanche"
16
+ __author__ = "Jayaram Kancherla"
19
17
  __copyright__ = "jkanche"
20
18
  __license__ = "MIT"
21
19
 
22
20
 
23
21
  class BiocFileCache:
24
- """
25
- Class to manage and cache files.
26
- """
22
+ """Class to manage and cache files."""
27
23
 
28
24
  def __init__(self, cacheDirOrPath: Union[str, Path] = create_tmp_dir()):
29
25
  """Initialize BiocFileCache.
30
26
 
31
27
  Args:
32
- cacheDirOrPath (Union[str, Path], optional): Path to cache.
33
- directory. Defaults to tmp location, `create_tmp_dir()`.
28
+ cacheDirOrPath:
29
+ Path to cache directory.
30
+
31
+ Defaults to tmp location, :py:func:`~.utils.create_tmp_dir`.
34
32
 
35
33
  Raises:
36
34
  Exception: Failed to initialize cache.
@@ -55,42 +53,64 @@ class BiocFileCache:
55
53
  self,
56
54
  rname: str,
57
55
  fpath: Union[str, Path],
58
- rtype: str = "local",
59
- action: str = "copy",
56
+ rtype: Literal["local", "web", "relative"] = "local",
57
+ action: Literal["copy", "move", "asis"] = "copy",
60
58
  ext: bool = False,
61
59
  ) -> Resource:
62
60
  """Add a resource from the provided `fpath` to cache as `rname`.
63
61
 
64
62
  Args:
65
- rname (str): Name of the resource to add to cache.
66
- fpath (Union[str, Path]): Location of the resource.
67
- rtype (str, optional): One of `"local"`, `"web"`, or `"relative"`.
68
- Defaults to `"local"`.
69
- action (str, optional): Either `"copy"`, `"move"` or `"asis"`.
70
- Defaults to `"copy"`.
71
- ext (bool, optional): Use filepath extension when storing in cache.
72
- Defaults to `False`.
63
+ rname:
64
+ Name of the resource to add to cache.
73
65
 
74
- Returns:
75
- Resource: Database record of the new resource in cache.
66
+ fpath:
67
+ Location of the resource.
68
+
69
+ rtype:
70
+ One of ``local``, ``web``, or ``relative``.
71
+ Defaults to ``local``.
72
+
73
+ action:
74
+ Either ``copy``, ``move`` or ``asis``.
75
+ Defaults to ``copy``.
76
+
77
+ ext:
78
+ Whether to use filepath extension when storing in cache.
79
+ Defaults to `False`.
76
80
 
77
81
  Raises:
78
- NoFpathError: When the `fpath` does not exist.
79
- RnameExistsError: When the `rname` already exists in the cache.
80
- sqlalchemy exceptions: When something is up with the cache.
82
+ NoFpathError:
83
+ When the `fpath` does not exist.
84
+
85
+ RnameExistsError:
86
+ When the `rname` already exists in the cache.
87
+ sqlalchemy exceptions: When something is up with the cache.
88
+
89
+ Returns:
90
+ Database record of the new resource in cache.
81
91
  """
82
92
  if isinstance(fpath, str):
83
93
  fpath = Path(fpath)
84
94
 
85
95
  if not fpath.exists():
86
- raise NoFpathError(f"Resource at {fpath} does not exist.")
96
+ raise NoFpathError(f"Resource at '{fpath}' does not exist.")
87
97
 
88
98
  rid = generate_id()
89
- rpath = f"{self.cache}/{rid}" + (f".{fpath.suffix}" if ext else "")
99
+ rpath = (
100
+ f"{self.cache}/{rid}" + (f".{fpath.suffix}" if ext else "")
101
+ if action != "asis"
102
+ else str(fpath)
103
+ )
90
104
 
91
105
  # create new record in the database
92
106
  res = Resource(
93
- **dict(rid=rid, rname=rname, rpath=rpath, rtype=rtype, fpath=str(fpath),)
107
+ **dict(
108
+ rid=rid,
109
+ rname=rname,
110
+ rpath=rpath,
111
+ rtype=rtype,
112
+ fpath=str(fpath),
113
+ )
94
114
  )
95
115
 
96
116
  # If this was higher up a parallel process could have added the key to
@@ -121,11 +141,15 @@ class BiocFileCache:
121
141
  """Search cache for a resource.
122
142
 
123
143
  Args:
124
- query (str): query or keywords to search.
125
- field (str, optional): Field to search. Defaults to "rname".
144
+ query:
145
+ Query string or keywords to search.
146
+
147
+ field:
148
+ Field to search.
149
+ Defaults to "rname".
126
150
 
127
151
  Returns:
128
- List[Resource]: list of matching resources from cache.
152
+ List of matching resources from cache.
129
153
  """
130
154
  with self.sessionLocal() as session:
131
155
  return (
@@ -138,11 +162,14 @@ class BiocFileCache:
138
162
  """Get a resource with `rname` from given `Session`.
139
163
 
140
164
  Args:
141
- session (Session): The `Session` object to use.
142
- rname (str): The `rname` of the `Resource` to get.
165
+ session:
166
+ The `Session` object to use.
167
+
168
+ rname:
169
+ The `rname` of the `Resource` to get.
143
170
 
144
171
  Returns:
145
- (Resource, optional): The `Resource` for the `rname` if any.
172
+ The `Resource` for the `rname` if available.
146
173
  """
147
174
  resource: Optional[Resource] = (
148
175
  session.query(Resource).filter(Resource.rname == rname).first()
@@ -164,13 +191,14 @@ class BiocFileCache:
164
191
  return resource
165
192
 
166
193
  def get(self, rname: str) -> Optional[Resource]:
167
- """get resource by name from cache.
194
+ """Get resource by name from cache.
168
195
 
169
196
  Args:
170
- rname (str): Name of the file to search.
197
+ rname:
198
+ Name of the file to search.
171
199
 
172
200
  Returns:
173
- Optional[Resource]: matched resource from cache if exists.
201
+ Matched `Resource` from cache if exists.
174
202
  """
175
203
  return self._get(self.sessionLocal(), rname)
176
204
 
@@ -178,7 +206,8 @@ class BiocFileCache:
178
206
  """Remove a resource from cache by name.
179
207
 
180
208
  Args:
181
- rname (str): Name of the resource to remove.
209
+ rname:
210
+ Name of the resource to remove.
182
211
  """
183
212
  with self.sessionLocal() as session:
184
213
  res: Optional[Resource] = self._get(session, rname)
@@ -194,18 +223,30 @@ class BiocFileCache:
194
223
  for file in os.scandir(self.cache):
195
224
  os.remove(file.path)
196
225
 
226
+ return True
227
+
197
228
  def update(
198
- self, rname: str, fpath: Union[str, Path], action: str = "copy"
229
+ self,
230
+ rname: str,
231
+ fpath: Union[str, Path],
232
+ action: Literal["copy", "move", "asis"] = "copy",
199
233
  ) -> Resource:
200
234
  """Update a resource in cache.
201
235
 
202
236
  Args:
203
- rname (str): name of the resource in cache.
204
- fpath (Union[str, Path]): new resource to replace existing file in cache.
205
- action (str, optional): either copy of move. defaults to copy.
237
+ rname:
238
+ Name of the resource in cache.
239
+
240
+ fpath:
241
+ New resource to replace existing file in cache.
242
+
243
+ action:
244
+ Either ``copy``, ``move`` or ``asis``.
245
+
246
+ Defaults to ``copy``.
206
247
 
207
248
  Returns:
208
- Resource: Updated resource record in cache.
249
+ Updated resource record in cache.
209
250
  """
210
251
 
211
252
  if isinstance(fpath, str):
@@ -218,8 +259,12 @@ class BiocFileCache:
218
259
  res = self._get(session, rname)
219
260
 
220
261
  if res is not None:
221
- # copy the file to cache
222
- copy_or_move(str(fpath), str(res.rpath), rname, action)
262
+ if action != "asis":
263
+ # copy the file to cache
264
+ copy_or_move(str(fpath), str(res.rpath), rname, action)
265
+ else:
266
+ res.rpath = str(fpath)
267
+
223
268
  res.access_time = res.last_modified_time = func.now()
224
269
  session.merge(res)
225
270
  session.commit()
@@ -1,9 +1,10 @@
1
+ from typing import Tuple
2
+
1
3
  from sqlalchemy import create_engine
2
4
  from sqlalchemy.engine import Engine
3
5
 
4
6
  # from sqlalchemy.ext.declarative import declarative_base
5
- from sqlalchemy.orm import sessionmaker, declarative_base
6
- from typing import Tuple
7
+ from sqlalchemy.orm import declarative_base, sessionmaker
7
8
 
8
9
  __author__ = "jkanche"
9
10
  __copyright__ = "jkanche"
@@ -13,13 +14,14 @@ Base = declarative_base()
13
14
 
14
15
 
15
16
  def create_schema(cache_dir: str) -> Tuple[Engine, sessionmaker]:
16
- """Create the schema in the sqlite database
17
+ """Create the schema in the sqlite database.
17
18
 
18
19
  Args:
19
- cache_dir (str): Location where the cache directory
20
+ cache_dir:
21
+ Location where the cache directory.
20
22
 
21
23
  Returns:
22
- a tuple of sqlalchemy engine and session maker
24
+ A tuple of sqlalchemy engine and session maker.
23
25
  """
24
26
  try:
25
27
  engine = create_engine(
@@ -33,4 +33,3 @@ class Resource(Base):
33
33
 
34
34
  def __repr__(self):
35
35
  return "<Resource(id='%s', rname='%s')>" % (self.id, self.rname)
36
-
pybiocfilecache/utils.py CHANGED
@@ -1,18 +1,21 @@
1
+ import logging
2
+ import sys
1
3
  import tempfile
2
4
  import uuid
3
5
  from pathlib import Path
4
6
  from shutil import copy2, move
7
+ from typing import Literal, Union
5
8
 
6
- from typing import Union
7
- import logging
8
- import sys
9
+ __author__ = "Jayaram Kancherla"
10
+ __copyright__ = "jkanche"
11
+ __license__ = "MIT"
9
12
 
10
13
 
11
14
  def create_tmp_dir() -> str:
12
- """create a temporary directory.
15
+ """Create a temporary directory.
13
16
 
14
17
  Returns:
15
- str: path to the directory
18
+ Temporary path to the directory.
16
19
  """
17
20
  return tempfile.mkdtemp()
18
21
 
@@ -21,43 +24,61 @@ def generate_id() -> str:
21
24
  """Generate uuid.
22
25
 
23
26
  Returns:
24
- str: unique string for use as id
27
+ Unique string for use as id.
25
28
  """
26
29
  return uuid.uuid4().hex
27
30
 
28
31
 
29
32
  def copy_or_move(
30
- source: Union[str, Path], target: Union[str, Path], rname: str, action: str = "copy"
33
+ source: Union[str, Path],
34
+ target: Union[str, Path],
35
+ rname: str,
36
+ action: Literal["copy", "move", "asis"] = "copy",
31
37
  ) -> None:
32
- """Copy or move a resource from `source` to `target`
38
+ """Copy or move a resource from ``source`` to ``target``.
33
39
 
34
40
  Args:
35
- source (Union[str, Path]): source location of the resource to copy of move.
36
- target (Union[str, Path]): destination to copy of move to.
37
- rname (str): Name of resource to add to cache
38
- action (str): copy of move file from source. Defaults to copy.
41
+ source:
42
+ Source location of the resource to copy of move.
43
+
44
+ target:
45
+ Destination to copy of move to.
46
+
47
+ rname:
48
+ Name of resource to add to cache.
49
+
50
+ action:
51
+ Copy of move file from source.
52
+ Defaults to copy.
39
53
 
40
54
  Raises:
41
- ValueError: if action is not `copy` or `move`.
42
- Exception: Error storing resource in the cache directory.
55
+ ValueError:
56
+ If action is not `copy`, `move` or `asis`.
57
+
58
+ Exception:
59
+ Error storing resource in the cache directory.
43
60
  """
44
61
 
45
- if action not in ["copy", "move"]:
46
- raise ValueError(f"Action must be either 'move' or 'copy', provided {action}")
62
+ if action not in ["copy", "move", "asis"]:
63
+ raise ValueError(
64
+ f"Action must be either 'move', 'copy' or 'asis', provided {action}."
65
+ )
47
66
 
48
67
  try:
49
68
  if action == "copy":
50
69
  copy2(source, target)
51
70
  elif action == "move":
52
71
  move(str(source), target)
72
+ elif action == "asis":
73
+ pass
53
74
  except Exception as e:
54
75
  raise Exception(
55
- f"Error storing resource: '{rname}' from: '{source}' in '{target}'",
76
+ f"Error storing resource: '{rname}' from: '{source}' in '{target}'.",
56
77
  ) from e
57
78
 
58
79
 
59
80
  def setup_logging(loglevel):
60
- """Setup basic logging
81
+ """Setup basic logging.
61
82
 
62
83
  Args:
63
84
  loglevel (int): minimum loglevel for emitting messages
@@ -1,13 +0,0 @@
1
- pybiocfilecache/BiocFileCache.py,sha256=FzU4RI5n9_lLmbvQUH-1iZNJVXjZK02ZUYAuUhMn3lE,8047
2
- pybiocfilecache/__init__.py,sha256=5SUhxaA5370FRyHOs5miL4WXxe2fNODbO_I6VRqDCB0,915
3
- pybiocfilecache/_exceptions.py,sha256=347Lt1Rrt-TTzP5yEqlRM1QoaPBXB1UnZXv0GfhZmv0,374
4
- pybiocfilecache/utils.py,sha256=HL_VagKHu2HlwT8ODID43ESOD1ERqSwDOGeQHHe8-YA,1782
5
- pybiocfilecache/db/Base.py,sha256=vfOWyRKFqPj4L4esuWb0MeCGu04xAz5bhAI1nl8IGjU,938
6
- pybiocfilecache/db/__init__.py,sha256=XE1DrTqLmDOM4Y4Qt3fdr6ahir5Vqug5e5v-DQexCDw,102
7
- pybiocfilecache/db/schema.py,sha256=7Qx6mUw5LeJYwZqikIox_H429Ko24mHYz7vey4zLUrA,1042
8
- pyBiocFileCache-0.2.2.dist-info/AUTHORS.md,sha256=j3yqoTV-_uShE0VwsxvcmANNhbMdudixmiBL-5cUCFo,111
9
- pyBiocFileCache-0.2.2.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
- pyBiocFileCache-0.2.2.dist-info/METADATA,sha256=qCr7P3VRNAhoLd0yN8eqS72-uE7ybeyyfI_k6vZTxPM,2200
11
- pyBiocFileCache-0.2.2.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
12
- pyBiocFileCache-0.2.2.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
- pyBiocFileCache-0.2.2.dist-info/RECORD,,