[docs]defget_assets(asset_id,asset_file,skip_md5=False):"""Handles automatic download and verification of external assets (such as forcing files). By default, assets are stored in ``$HOME/.veros/assets`` (can be overwritten by setting ``VEROS_ASSET_DIR`` environment variable to the desired location). Arguments: asset_id (str): Identifier of the collection of assets. Should be unique for each setup. asset_file (str): JSON file containing URLs and (optionally) MD5 hashsums of each asset. skip_md5 (bool): Whether to skip MD5 checksum validation (useful for huge asset files) Returns: A ``dict``-like mapping of each asset to file name on disk. Assets are downloaded lazily. Example: >>> assets = get_assets('mysetup', 'assets.json') >>> assets['forcing'] "/home/user/.veros/assets/mysetup/mysetup_forcing.h5", "initial_conditions": "/home/user/.veros/assets/mysetup/initial.h5" } In this case, ``assets.json`` contains:: { "forcing": { "url": "https://mywebsite.com/veros_assets/mysetup_forcing.h5", "md5": "ef3be0a58782771c8ee5a6d0206b87f6" }, "initial_conditions": { "url": "https://mywebsite.com/veros_assets/initial.h5", "md5": "d1b4e0e199d7a5883cf7c88d3d6bcb28" } } """withopen(asset_file,"r")asf:assets=json.load(f)asset_dir=os.path.join(ASSET_DIRECTORY,asset_id)ifnotos.path.isdir(asset_dir):try:# possible race-conditionos.makedirs(asset_dir)exceptOSError:ifos.path.isdir(asset_dir):passreturnAssetStore(asset_dir,assets,skip_md5)
def_download_file(url,target_path,timeout=10):"""Download a file and save it to a folder"""tmpfile=f"{target_path}.incomplete"withrequests.get(url,stream=True,timeout=timeout)asresponse:response.raise_for_status()response.raw.decode_content=Truetry:withopen(tmpfile,"wb")asdst:shutil.copyfileobj(response.raw,dst)except:# noqa: E722os.remove(tmpfile)raiseshutil.move(tmpfile,target_path)returntarget_pathdef_filehash(path):hash_md5=hashlib.md5()withopen(path,"rb")asf:forchunkiniter(lambda:f.read(4096),b""):hash_md5.update(chunk)returnhash_md5.hexdigest()