11from abc import abstractmethod
22import os
33from pathlib import Path
4+ import shutil
5+ import tempfile
46from typing import Dict , List , Type
57
8+ from eth_typing import URI
69from eth_utils import import_string , to_bytes
710import ipfshttpclient
811
@@ -49,6 +52,18 @@ def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
4952 """
5053 pass
5154
55+ def write_to_disk (self , uri : URI , target_path : Path ) -> None :
56+ contents = self .fetch_uri_contents (uri )
57+ if target_path .exists ():
58+ raise CannotHandleURI (
59+ f"IPFS uri: { uri } cannot be written to disk since target path ({ target_path } ) "
60+ "already exists. Please provide a target_path that does not exist."
61+ )
62+ with tempfile .NamedTemporaryFile () as temp :
63+ temp .write (contents )
64+ temp .seek (0 )
65+ shutil .copyfile (temp .name , target_path )
66+
5267
5368class IPFSOverHTTPBackend (BaseIPFSBackend ):
5469 """
@@ -59,7 +74,7 @@ class IPFSOverHTTPBackend(BaseIPFSBackend):
5974 def __init__ (self ) -> None :
6075 self .client = ipfshttpclient .connect (self .base_uri )
6176
62- def fetch_uri_contents (self , uri : str ) -> bytes :
77+ def fetch_uri_contents (self , uri : URI ) -> bytes :
6378 ipfs_hash = extract_ipfs_path_from_uri (uri )
6479 contents = self .client .cat (ipfs_hash )
6580 validation_hash = generate_file_hash (contents )
@@ -108,6 +123,11 @@ def fetch_uri_contents(self, uri: str) -> bytes:
108123 "IPFS gateway is currently disabled, please use a different IPFS backend."
109124 )
110125
126+ def write_to_disk (self , uri : URI , target_path : Path ) -> None :
127+ raise CannotHandleURI (
128+ "IPFS gateway is currently disabled, please use a different IPFS backend."
129+ )
130+
111131
112132class InfuraIPFSBackend (IPFSOverHTTPBackend ):
113133 """
0 commit comments