Ipfs

ipfskvs.ipfs.Ipfs dataclass

IPFS Python Client.

This client uses the ipfs rpc via http. The ipfs server or gateway is specified in the constructor.

Usage

For testing with a local ipfs node

    from ipfskvs.ipfs import Ipfs

    client = Ipfs()  # defaults to http://127.0.0.1:5001/api/v0
    client.mkdir("my_dir")
    client.add("my_dir/my_file", b"my_contents")
References
IPFS RPC documentation

https://docs.ipfs.tech/reference/kubo/rpc/#api-v0-files-write

For more information about ipfs

https://docs.ipfs.tech/concepts/what-is-ipfs/#defining-ipfs

Source code in ipfskvs/ipfs.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
@dataclass
class Ipfs():
    """IPFS Python Client.

    This client uses the ipfs rpc via http.
    The ipfs server or gateway is specified in the constructor.

    ### Usage
    For testing with a local ipfs node
    ```py
        from ipfskvs.ipfs import Ipfs

        client = Ipfs()  # defaults to http://127.0.0.1:5001/api/v0
        client.mkdir("my_dir")
        client.add("my_dir/my_file", b"my_contents")
    ```

    ### References

    IPFS RPC documentation:
        https://docs.ipfs.tech/reference/kubo/rpc/#api-v0-files-write

    For more information about ipfs:
        https://docs.ipfs.tech/concepts/what-is-ipfs/#defining-ipfs
    """
    host: str
    port: int
    version: str

    def __init__(
            self: Self,
            host: str = "http://127.0.0.1",
            port: int = 5001,
            version: str = "v0") -> None:
        """Create an IPFS client.

        Args:
            host (str, optional): IPFS server host or gateway host. Defaults to "http://127.0.0.1".  # noqa: E501
            port (int, optional): IPFS port. Defaults to 5001.
            version (str, optional): IPFS rpc version. Defaults to "v0".
        """
        self.host = host
        self.port = port
        self.version = version

    def _make_request(
            self: Self,
            endpoint: str,
            params: dict = None,
            files: dict = None,
            raise_for_status: bool = True) -> bytes:
        """Make an http request for an IPFS RPC call.

        Args:
            endpoint (str): The IPFS RPC endpoint
            params (dict, optional): The RPC params. Defaults to None.
            files (dict, optional): The RPC files. Defaults to None.
            raise_for_status (bool, optional): If true, raise any
                exceptions that are caught. Defaults to True.

        Returns:
            bytes: The http response data
        """
        url = f"{self.host}:{self.port}/api/{self.version}/{endpoint}"
        LOG.info(f"HTTP POST; url: {url} params: {params} files: {files}")
        response = requests.post(url, params=params, files=files)
        if raise_for_status:
            response.raise_for_status()

        LOG.debug(response.content)
        return response.content

    def _dag_put(self: Self, data: bytes) -> str:
        """Call the dag/put endpoint.

        Args:
            data (bytes): The raw object data

        Raises:
            RuntimeError: An exception is raised for any RPC errors

        Returns:
            str: The RPC response
        """
        try:
            response = self._make_request(
                endpoint="dag/put",
                params={
                    "store-codec": "raw",
                    "input-codec": "raw"
                },
                files={
                    "object data": add_prefix('raw', data)
                },
                raise_for_status=False
            )
            result = json.loads(response.decode())
            return result["Cid"]["/"]
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def _dag_get(self: Self, filename: str) -> str:
        """Call the dag/get endpoint.

        Args:
            filename (str): The filename to get the dag for

        Raises:
            RuntimeError: An exception is raised for any RPC errors

        Returns:
            str: The RPC response
        """
        try:
            response = self._make_request(
                endpoint="dag/get",
                params={
                    "arg": filename,
                    # "output-codec": "raw"
                },
                raise_for_status=False
            )
            return json.loads(response.decode())
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def mkdir(self: Self, directory_name: str, with_home: bool = True) -> None:
        """Create a directory in ipfs.

        Args:
            directory_name (str): The name of the directory to create
            with_home (bool, optional): If true, include Ipfs.IPFS_HOME
                as a directory prefix. Defaults to True.

        Raises:
            RuntimeError: An exception is raised for any RPC errors
        """
        # Split the filename into its directory and basename components
        parts = os.path.split(directory_name)

        # If the directory part is not empty, create it recursively
        if parts[0]:
            self.mkdir(parts[0])

        path = f"{IPFS_HOME}/{directory_name}" if with_home else f"/{directory_name}"  # noqa: E501
        try:
            self._make_request(
                endpoint="files/mkdir",
                params={"arg": path},
                raise_for_status=False
            )
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def read(self: Self, filename: str) -> bytes:
        """Read a file from ipfs.

        Args:
            filename (str): The file to read

        Returns:
            (bytes): The file contents
        """
        try:
            return self._make_request(
                endpoint="files/read",
                params={"arg": f"{IPFS_HOME}/{filename}"},
            )
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def write(self: Self, filename: str, data: bytes) -> None:
        """Overwrite file contents in ipfs.

        Args:
            filename (str): The filename to write to
            data (bytes): The data to write

        Raises:
            NotImplementedError: This function is not implemented.
                For now, just use `add` and `delete`
        """
        raise NotImplementedError("For now, just use `add` and `delete`")

        try:
            stat = self.stat(filename)
            dag = self._dag_get(stat["Hash"])
            # print(dag)
            # print(dag["/"]["bytes"].encode)
            example = Example()
            example.ParseFromString(dag)
            self._make_request(
                endpoint="files/write",
                params={
                    "arg": f"{IPFS_HOME}/{filename}",
                    "truncate": True,
                    "raw-leaves": True
                },
                files={
                    'file': example.SerializeToString()
                }
            )
        except requests.exceptions.HTTPError as e:
            raise RuntimeError(e.response._content.decode()) from e

    def add(self: Self, filename: str, data: bytes) -> None:
        """Create a new file in ipfs.

        This does not work for updating existing files.

        Args:
            filename (str): The filename for the uploaded data
            data (bytes): The data that will be written to the new file
        """
        # Split the filename into its directory and basename components
        parts = os.path.split(filename)

        # If the directory part is not empty, create it recursively
        if parts[0]:
            self.mkdir(parts[0])

        try:
            self._make_request(
                endpoint="add",
                params={
                    "to-files": f"{IPFS_HOME}/{filename}",
                    "raw-leaves": True
                },
                files={
                    'file': data
                }
            )
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def does_file_exist(self: Self, filename: str) -> bool:
        """Check if a file exists in ipfs.

        Args:
            filename (str): The file to check

        Returns:
            bool: True if the file exists, false otherwise
        """
        try:
            response = self._make_request(
                endpoint="files/stat",
                params={"arg": f"{IPFS_HOME}/{filename}"},
                raise_for_status=False
            )
            return 'file does not exist' not in response.decode()
        except Exception as e:
            LOG.error(e)
            if 'file does not exist' in e.response._content.decode():
                return False

            raise RuntimeError(e.response._content.decode()) from e

    def stat(self: Self, filename: str) -> bytes:
        """Call the files/stat endpoint.

        Args:
            filename (str): The path to search on ipfs

        Returns:
            bytes: The RPC response
        """
        try:
            return json.loads(self._make_request(
                endpoint="files/stat",
                params={"arg": f"{IPFS_HOME}/{filename}"},
                raise_for_status=False
            ))
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def list_files(self: Self, prefix: str = "") -> List[str]:
        """List the ipfs files in a directory.

        Args:
            prefix (str): The path to search on ipfs

        Returns:
            List[str]: The list of filenames found at that location
        """
        try:
            return json.loads(self._make_request(
                endpoint="files/ls",
                params={"arg": f"{IPFS_HOME}/{prefix}"},
                raise_for_status=False
            ))
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

    def delete(self: Self, filename: str) -> None:
        """Delete a file from ipfs.

        Args:
            filename (str): The filename to delete
        """
        try:
            self._make_request(
                endpoint="files/rm",
                params={
                    "arg": f"{IPFS_HOME}/{filename}",
                    "recursive": True
                },
                raise_for_status=False
            )
        except Exception as e:
            LOG.error(e)
            raise RuntimeError(e.response._content.decode()) from e

__init__(host='http://127.0.0.1', port=5001, version='v0')

Create an IPFS client.

Parameters:

Name Type Description Default
host str

IPFS server host or gateway host. Defaults to "http://127.0.0.1". # noqa: E501

'http://127.0.0.1'
port int

IPFS port. Defaults to 5001.

5001
version str

IPFS rpc version. Defaults to "v0".

'v0'
Source code in ipfskvs/ipfs.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(
        self: Self,
        host: str = "http://127.0.0.1",
        port: int = 5001,
        version: str = "v0") -> None:
    """Create an IPFS client.

    Args:
        host (str, optional): IPFS server host or gateway host. Defaults to "http://127.0.0.1".  # noqa: E501
        port (int, optional): IPFS port. Defaults to 5001.
        version (str, optional): IPFS rpc version. Defaults to "v0".
    """
    self.host = host
    self.port = port
    self.version = version

_make_request(endpoint, params=None, files=None, raise_for_status=True)

Make an http request for an IPFS RPC call.

Parameters:

Name Type Description Default
endpoint str

The IPFS RPC endpoint

required
params dict

The RPC params. Defaults to None.

None
files dict

The RPC files. Defaults to None.

None
raise_for_status bool

If true, raise any exceptions that are caught. Defaults to True.

True

Returns:

Name Type Description
bytes bytes

The http response data

Source code in ipfskvs/ipfs.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def _make_request(
        self: Self,
        endpoint: str,
        params: dict = None,
        files: dict = None,
        raise_for_status: bool = True) -> bytes:
    """Make an http request for an IPFS RPC call.

    Args:
        endpoint (str): The IPFS RPC endpoint
        params (dict, optional): The RPC params. Defaults to None.
        files (dict, optional): The RPC files. Defaults to None.
        raise_for_status (bool, optional): If true, raise any
            exceptions that are caught. Defaults to True.

    Returns:
        bytes: The http response data
    """
    url = f"{self.host}:{self.port}/api/{self.version}/{endpoint}"
    LOG.info(f"HTTP POST; url: {url} params: {params} files: {files}")
    response = requests.post(url, params=params, files=files)
    if raise_for_status:
        response.raise_for_status()

    LOG.debug(response.content)
    return response.content

_dag_put(data)

Call the dag/put endpoint.

Parameters:

Name Type Description Default
data bytes

The raw object data

required

Raises:

Type Description
RuntimeError

An exception is raised for any RPC errors

Returns:

Name Type Description
str str

The RPC response

Source code in ipfskvs/ipfs.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def _dag_put(self: Self, data: bytes) -> str:
    """Call the dag/put endpoint.

    Args:
        data (bytes): The raw object data

    Raises:
        RuntimeError: An exception is raised for any RPC errors

    Returns:
        str: The RPC response
    """
    try:
        response = self._make_request(
            endpoint="dag/put",
            params={
                "store-codec": "raw",
                "input-codec": "raw"
            },
            files={
                "object data": add_prefix('raw', data)
            },
            raise_for_status=False
        )
        result = json.loads(response.decode())
        return result["Cid"]["/"]
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

_dag_get(filename)

Call the dag/get endpoint.

Parameters:

Name Type Description Default
filename str

The filename to get the dag for

required

Raises:

Type Description
RuntimeError

An exception is raised for any RPC errors

Returns:

Name Type Description
str str

The RPC response

Source code in ipfskvs/ipfs.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def _dag_get(self: Self, filename: str) -> str:
    """Call the dag/get endpoint.

    Args:
        filename (str): The filename to get the dag for

    Raises:
        RuntimeError: An exception is raised for any RPC errors

    Returns:
        str: The RPC response
    """
    try:
        response = self._make_request(
            endpoint="dag/get",
            params={
                "arg": filename,
                # "output-codec": "raw"
            },
            raise_for_status=False
        )
        return json.loads(response.decode())
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

mkdir(directory_name, with_home=True)

Create a directory in ipfs.

Parameters:

Name Type Description Default
directory_name str

The name of the directory to create

required
with_home bool

If true, include Ipfs.IPFS_HOME as a directory prefix. Defaults to True.

True

Raises:

Type Description
RuntimeError

An exception is raised for any RPC errors

Source code in ipfskvs/ipfs.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def mkdir(self: Self, directory_name: str, with_home: bool = True) -> None:
    """Create a directory in ipfs.

    Args:
        directory_name (str): The name of the directory to create
        with_home (bool, optional): If true, include Ipfs.IPFS_HOME
            as a directory prefix. Defaults to True.

    Raises:
        RuntimeError: An exception is raised for any RPC errors
    """
    # Split the filename into its directory and basename components
    parts = os.path.split(directory_name)

    # If the directory part is not empty, create it recursively
    if parts[0]:
        self.mkdir(parts[0])

    path = f"{IPFS_HOME}/{directory_name}" if with_home else f"/{directory_name}"  # noqa: E501
    try:
        self._make_request(
            endpoint="files/mkdir",
            params={"arg": path},
            raise_for_status=False
        )
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

read(filename)

Read a file from ipfs.

Parameters:

Name Type Description Default
filename str

The file to read

required

Returns:

Type Description
bytes

The file contents

Source code in ipfskvs/ipfs.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def read(self: Self, filename: str) -> bytes:
    """Read a file from ipfs.

    Args:
        filename (str): The file to read

    Returns:
        (bytes): The file contents
    """
    try:
        return self._make_request(
            endpoint="files/read",
            params={"arg": f"{IPFS_HOME}/{filename}"},
        )
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

add(filename, data)

Create a new file in ipfs.

This does not work for updating existing files.

Parameters:

Name Type Description Default
filename str

The filename for the uploaded data

required
data bytes

The data that will be written to the new file

required
Source code in ipfskvs/ipfs.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def add(self: Self, filename: str, data: bytes) -> None:
    """Create a new file in ipfs.

    This does not work for updating existing files.

    Args:
        filename (str): The filename for the uploaded data
        data (bytes): The data that will be written to the new file
    """
    # Split the filename into its directory and basename components
    parts = os.path.split(filename)

    # If the directory part is not empty, create it recursively
    if parts[0]:
        self.mkdir(parts[0])

    try:
        self._make_request(
            endpoint="add",
            params={
                "to-files": f"{IPFS_HOME}/{filename}",
                "raw-leaves": True
            },
            files={
                'file': data
            }
        )
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

does_file_exist(filename)

Check if a file exists in ipfs.

Parameters:

Name Type Description Default
filename str

The file to check

required

Returns:

Name Type Description
bool bool

True if the file exists, false otherwise

Source code in ipfskvs/ipfs.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def does_file_exist(self: Self, filename: str) -> bool:
    """Check if a file exists in ipfs.

    Args:
        filename (str): The file to check

    Returns:
        bool: True if the file exists, false otherwise
    """
    try:
        response = self._make_request(
            endpoint="files/stat",
            params={"arg": f"{IPFS_HOME}/{filename}"},
            raise_for_status=False
        )
        return 'file does not exist' not in response.decode()
    except Exception as e:
        LOG.error(e)
        if 'file does not exist' in e.response._content.decode():
            return False

        raise RuntimeError(e.response._content.decode()) from e

stat(filename)

Call the files/stat endpoint.

Parameters:

Name Type Description Default
filename str

The path to search on ipfs

required

Returns:

Name Type Description
bytes bytes

The RPC response

Source code in ipfskvs/ipfs.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def stat(self: Self, filename: str) -> bytes:
    """Call the files/stat endpoint.

    Args:
        filename (str): The path to search on ipfs

    Returns:
        bytes: The RPC response
    """
    try:
        return json.loads(self._make_request(
            endpoint="files/stat",
            params={"arg": f"{IPFS_HOME}/{filename}"},
            raise_for_status=False
        ))
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

list_files(prefix='')

List the ipfs files in a directory.

Parameters:

Name Type Description Default
prefix str

The path to search on ipfs

''

Returns:

Type Description
List[str]

List[str]: The list of filenames found at that location

Source code in ipfskvs/ipfs.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def list_files(self: Self, prefix: str = "") -> List[str]:
    """List the ipfs files in a directory.

    Args:
        prefix (str): The path to search on ipfs

    Returns:
        List[str]: The list of filenames found at that location
    """
    try:
        return json.loads(self._make_request(
            endpoint="files/ls",
            params={"arg": f"{IPFS_HOME}/{prefix}"},
            raise_for_status=False
        ))
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e

delete(filename)

Delete a file from ipfs.

Parameters:

Name Type Description Default
filename str

The filename to delete

required
Source code in ipfskvs/ipfs.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def delete(self: Self, filename: str) -> None:
    """Delete a file from ipfs.

    Args:
        filename (str): The filename to delete
    """
    try:
        self._make_request(
            endpoint="files/rm",
            params={
                "arg": f"{IPFS_HOME}/{filename}",
                "recursive": True
            },
            raise_for_status=False
        )
    except Exception as e:
        LOG.error(e)
        raise RuntimeError(e.response._content.decode()) from e