18 from typing
import Any, Union
19 from pathlib
import Path
28 from ._folder_manager
import folder_manager
34 Exception which is raised due to any unexpected behaviour with Cache module
40 def _hashCacheKey(key: str) -> str:
41 return hashlib.sha256(key.encode(
"UTF-8")).hexdigest()
47 def _download(source: str, destination: Path, retryCount: int = 0) -> Path:
48 if destination.exists():
49 raise FileExistsError(destination)
52 with requests.get(source, stream =
True)
as r:
55 with destination.open(
"wb")
as destinationFile:
56 for chunk
in r.iter_content(chunk_size = 8192):
57 destinationFile.write(chunk)
59 if retryCount >= MAX_RETRY_COUNT:
62 destination.unlink(missing_ok =
True)
63 return _download(source, destination, retryCount + 1)
68 def getPath(key: str) -> Path:
70 Retrieves the path of the cache
75 key to which the cache item was linked
79 pathlib.Path -> path of the cached item
83 CacheException -> if something went wrong
87 >>> from coretex import cache
90 >>> print(cache.getPath(key))
91 Path("/Users/dummyUser/.coretex/cache/c147efcfc2d7ea666a9e4f5187b115c90903f0fc896a56df9a6ef5d8f3fc9f31.zip")
95 raise CacheException(
">> [Coretex] Cache with given key doesn't exist.")
97 return folder_manager.cache / _hashCacheKey(key)
100 def exists(key: str) -> bool:
102 Checks if the cache item exists
107 key to which the cache item was linked
111 bool -> True if it exists, False otherwise
115 >>> from coretex import cache
117 >>> key = "dummyFile"
118 >>> print(cache.exists(key))
122 return folder_manager.cache.joinpath(_hashCacheKey(key)).exists()
125 def remove(key: str) ->
None:
127 Removes cached item from the cache
131 key : str -> Key to which the cache item was linked
135 CacheException -> if the cache item does not exist
139 >>> from coretex import cache
141 >>> cache.remove("dummyFile")
145 raise CacheException(
">> [Coretex] Cache with given key doesn't exist.")
147 getPath(key).unlink()
152 Clears all cached items
156 >>> from coretex import cache
161 shutil.rmtree(folder_manager.cache)
164 def storeObject(key: str, object: Any, override: bool =
False) ->
None:
166 Caches the specified object using pickle
171 key to which the cached object will be linked
173 object which supports being pickled
175 should the cache be overriden if it exists or not
179 CacheException -> if something went wrong
183 >>> from coretex import cache
185 >>> dummyObject = {"name": "John", "age": 24, "gender": "Male"}
186 >>> cache.storeObject("Person", dummyObject)
189 if not override
and exists(key):
190 raise CacheException(
">> [Coretex] Cache with given key already exists. Set \"override\" to \"True\" if you want to override existing cache.")
192 if override
and exists(key):
193 getPath(key).unlink()
195 cachePath = folder_manager.cache / _hashCacheKey(key)
196 with cachePath.open(
"wb")
as cacheFile:
197 pickle.dump(object, cacheFile)
200 def storeFile(key: str, source: Union[Path, str], override: bool =
False) ->
None:
202 Caches the specified file
207 key to which the cached file will be linked
209 path to the file which will be cached
211 should the cache be overriden if it exists or not
215 CacheException -> if something went wrong
219 >>> from coretex import cache
221 >>> filePath = "path/to/file"
222 >>> cache.storeFile("dummyFile", filePath)
225 if not isinstance(source, Path):
226 source = Path(source)
228 if not override
and exists(key):
229 raise CacheException(
">> [Coretex] Cache with given key already exists. Set \"override\" to \"True\" if you want to override existing cache.")
231 if override
and exists(key):
232 getPath(key).unlink()
234 cachePath = folder_manager.cache / _hashCacheKey(key)
237 os.link(source, cachePath)
240 def storeUrl(key: str, url: str, override: bool =
False) ->
None:
242 Downloads and caches file from the specified URL
247 URL of the file which is downloaded
249 Name of the downloaded file with extension - used as a key for cache
253 Tuple[Path, str] -> Path of the cached file and the name of the cached file
257 CacheException -> if something went wrong
261 >>> from coretex import cache
263 >>> url = "https://dummy_url.com/download"
264 >>> fileName = "dummyFile.ext"
265 >>> cache.storeUrl(url, fileName)
268 if not override
and exists(key):
269 raise CacheException(
">> [Coretex] Cache with given key already exists. Set \"override\" to \"True\" if you want to override existing cache.")
271 if override
and exists(key):
272 getPath(key).unlink()
274 cachePath = folder_manager.cache / _hashCacheKey(key)
275 _download(url, cachePath)
278 def loadObject(key: str) -> Any:
280 Loads the object cached with storeObject function
285 key to which the object was linked when cached
289 Any -> unpickled object
293 CacheException -> if something went wrong
297 >>> from coretex import cache
299 >>> loadedObject = cache.load("dummyObject")
300 >>> print(loadedObject)
301 {"name": "John", "age": 24, "gender": "Male"}
305 raise CacheException(
">> [Coretex] Cache with given key doesn't exist.")
307 with getPath(key).open(
"rb")
as pickleFile:
308 return pickle.load(pickleFile)