如何在Python中将多个文件添加到IPFS?

3

我是一个初学者,试图在IPFS网络上上传和访问数据。我正在跟随同一教程。这是他们网站上的代码。

# upload
import requests
import json

files = {
    'fileOne': ('Congrats! This is the first sentence'),
}

response = requests.post('https://ipfs.infura.io:5001/api/v0/add', files=files)
p = response.json()
hash = p['Hash']
print(hash)

# retreive
params = (
    ('arg', hash),
)
response_two = requests.post('https://ipfs.infura.io:5001/api/v0/block/get', params=params)
print(response_two.text)

我尝试了一下,它可以正常工作。但是,与其只包含像这样1条记录的1个文件不同-

files = {
    'fileOne': ('Congrats! This is the first sentence'),
}

我想上传多个类似的文件,例如包含多行数据的员工详情。我已经尝试了多种方法但都没有成功。请问有人能告诉我如何做吗?谢谢。

1
您可以通过向files字典添加需要添加到IPFS的文件来扩展它。但是请注意,对于较大的文件,您可能需要逐块读取原始文件并流式传输请求。 - McSinyx
1个回答

3

您可以通过简单地增加您的files字典的大小一次添加多个文件:

files = {
    'fileOne': ('Congrats! This is the first sentence'),
    'fileTwo': ('''Congrats! This is the first sentence
        This is the second sentence.'''),
    'example': (open('example', 'rb')),
}

响应是一个JSON流,每个条目之间用换行符分隔。因此,您需要以不同的方式解析响应:

dec = json.JSONDecoder()
i = 0
while i < len(response.text):
    data, s = dec.raw_decode(response.text[i:])
    i += s+1
    print("%s: %s" % (data['Name'], data['Hash']))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接