pyBiocFileCache 0.3.0__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,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.3.0
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
@@ -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,,
@@ -3,17 +3,17 @@
3
3
  import os
4
4
  from pathlib import Path
5
5
  from time import sleep, time
6
- from typing import List, Optional, Union
6
+ from typing import List, Literal, Optional, Union
7
7
 
8
8
  from sqlalchemy import func
9
9
  from sqlalchemy.orm import Session
10
10
 
11
+ from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
11
12
  from .db import create_schema
12
13
  from .db.schema import Resource
13
14
  from .utils import copy_or_move, create_tmp_dir, generate_id
14
- from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
15
15
 
16
- __author__ = "jkanche"
16
+ __author__ = "Jayaram Kancherla"
17
17
  __copyright__ = "jkanche"
18
18
  __license__ = "MIT"
19
19
 
@@ -25,8 +25,10 @@ class BiocFileCache:
25
25
  """Initialize BiocFileCache.
26
26
 
27
27
  Args:
28
- cacheDirOrPath (Union[str, Path], optional): Path to cache.
29
- 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`.
30
32
 
31
33
  Raises:
32
34
  Exception: Failed to initialize cache.
@@ -51,38 +53,54 @@ class BiocFileCache:
51
53
  self,
52
54
  rname: str,
53
55
  fpath: Union[str, Path],
54
- rtype: str = "local",
55
- action: str = "copy",
56
+ rtype: Literal["local", "web", "relative"] = "local",
57
+ action: Literal["copy", "move", "asis"] = "copy",
56
58
  ext: bool = False,
57
59
  ) -> Resource:
58
60
  """Add a resource from the provided `fpath` to cache as `rname`.
59
61
 
60
62
  Args:
61
- rname (str): Name of the resource to add to cache.
62
- fpath (Union[str, Path]): Location of the resource.
63
- rtype (str, optional): One of `"local"`, `"web"`, or `"relative"`.
64
- Defaults to `"local"`.
65
- action (str, optional): Either `"copy"`, `"move"` or `"asis"`.
66
- Defaults to `"copy"`.
67
- ext (bool, optional): Use filepath extension when storing in cache.
68
- Defaults to `False`.
63
+ rname:
64
+ Name of the resource to add to cache.
69
65
 
70
- Returns:
71
- 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`.
72
80
 
73
81
  Raises:
74
- NoFpathError: When the `fpath` does not exist.
75
- RnameExistsError: When the `rname` already exists in the cache.
76
- 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.
77
91
  """
78
92
  if isinstance(fpath, str):
79
93
  fpath = Path(fpath)
80
94
 
81
95
  if not fpath.exists():
82
- raise NoFpathError(f"Resource at {fpath} does not exist.")
96
+ raise NoFpathError(f"Resource at '{fpath}' does not exist.")
83
97
 
84
98
  rid = generate_id()
85
- 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
+ )
86
104
 
87
105
  # create new record in the database
88
106
  res = Resource(
@@ -123,11 +141,15 @@ class BiocFileCache:
123
141
  """Search cache for a resource.
124
142
 
125
143
  Args:
126
- query (str): query or keywords to search.
127
- 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".
128
150
 
129
151
  Returns:
130
- List[Resource]: list of matching resources from cache.
152
+ List of matching resources from cache.
131
153
  """
132
154
  with self.sessionLocal() as session:
133
155
  return (
@@ -140,11 +162,14 @@ class BiocFileCache:
140
162
  """Get a resource with `rname` from given `Session`.
141
163
 
142
164
  Args:
143
- session (Session): The `Session` object to use.
144
- 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.
145
170
 
146
171
  Returns:
147
- (Resource, optional): The `Resource` for the `rname` if any.
172
+ The `Resource` for the `rname` if available.
148
173
  """
149
174
  resource: Optional[Resource] = (
150
175
  session.query(Resource).filter(Resource.rname == rname).first()
@@ -169,10 +194,11 @@ class BiocFileCache:
169
194
  """Get resource by name from cache.
170
195
 
171
196
  Args:
172
- rname (str): Name of the file to search.
197
+ rname:
198
+ Name of the file to search.
173
199
 
174
200
  Returns:
175
- Optional[Resource]: matched resource from cache if exists.
201
+ Matched `Resource` from cache if exists.
176
202
  """
177
203
  return self._get(self.sessionLocal(), rname)
178
204
 
@@ -180,7 +206,8 @@ class BiocFileCache:
180
206
  """Remove a resource from cache by name.
181
207
 
182
208
  Args:
183
- rname (str): Name of the resource to remove.
209
+ rname:
210
+ Name of the resource to remove.
184
211
  """
185
212
  with self.sessionLocal() as session:
186
213
  res: Optional[Resource] = self._get(session, rname)
@@ -196,18 +223,30 @@ class BiocFileCache:
196
223
  for file in os.scandir(self.cache):
197
224
  os.remove(file.path)
198
225
 
226
+ return True
227
+
199
228
  def update(
200
- 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",
201
233
  ) -> Resource:
202
234
  """Update a resource in cache.
203
235
 
204
236
  Args:
205
- rname (str): name of the resource in cache.
206
- fpath (Union[str, Path]): new resource to replace existing file in cache.
207
- 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``.
208
247
 
209
248
  Returns:
210
- Resource: Updated resource record in cache.
249
+ Updated resource record in cache.
211
250
  """
212
251
 
213
252
  if isinstance(fpath, str):
@@ -220,8 +259,12 @@ class BiocFileCache:
220
259
  res = self._get(session, rname)
221
260
 
222
261
  if res is not None:
223
- # copy the file to cache
224
- 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
+
225
268
  res.access_time = res.last_modified_time = func.now()
226
269
  session.merge(res)
227
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"
@@ -16,10 +17,11 @@ def create_schema(cache_dir: str) -> Tuple[Engine, sessionmaker]:
16
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(
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
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,38 +24,56 @@ 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
 
@@ -1,13 +0,0 @@
1
- pybiocfilecache/BiocFileCache.py,sha256=6L7uYANBSPkb6kEX8p-VYHCLOPPn4RUIveFDktSzXrI,8130
2
- pybiocfilecache/__init__.py,sha256=5SUhxaA5370FRyHOs5miL4WXxe2fNODbO_I6VRqDCB0,915
3
- pybiocfilecache/_exceptions.py,sha256=347Lt1Rrt-TTzP5yEqlRM1QoaPBXB1UnZXv0GfhZmv0,374
4
- pybiocfilecache/utils.py,sha256=NHgigiMzZ3LaQPDa2ydAH1f8ls4itZgCRbcB2qJwyjA,1783
5
- pybiocfilecache/db/Base.py,sha256=TuMk8Eqiu8rb7QZVtUYsGbVxMekn4UDyQ4vkvuCp22k,939
6
- pybiocfilecache/db/__init__.py,sha256=XE1DrTqLmDOM4Y4Qt3fdr6ahir5Vqug5e5v-DQexCDw,102
7
- pybiocfilecache/db/schema.py,sha256=alr2YCfCmYb7xt8pzXqwpY-eBLNA3oR4nD8ruVzHo6E,1041
8
- pyBiocFileCache-0.3.0.dist-info/AUTHORS.md,sha256=MMx3vll5oIcyk72Bk3N_ACfHWt5YhAlk2vBjx68m4R8,112
9
- pyBiocFileCache-0.3.0.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
- pyBiocFileCache-0.3.0.dist-info/METADATA,sha256=aBtQrklvKx2djCoo6ATN5D8V0ptkSyR0dLT4HfiXg6o,2535
11
- pyBiocFileCache-0.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
12
- pyBiocFileCache-0.3.0.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
- pyBiocFileCache-0.3.0.dist-info/RECORD,,