IPFS是一个分布式的存储系统,可以使用浏览器或客户端上传文件。本文介绍如何使用Python连接IPFS系统,实现文件的上传和查阅,需要用到的是Infura 提供的API。
首先导入需要用到的库:
import requests
import json
因为在国内infura并不能正常访问,所以需要使用代理。我电脑上的翻墙软件使用的代理协议是SOCKS5,为了让 requests 支持 SOCKS5,需要先对它进行升级。(如果使用的是HTTP代理协议就不用升级。)
pip install -U requests[socks5]
然后就可以设置代理如下:
proxies = {
"http": "socks5://127.0.0.1:10808",
"https": "socks5://127.0.0.1:10808",
}
接下来指定上传的文件,这里用一行简单的文字表示。
add_url = 'https://ipfs.infura.io:5001/api/v0/add'
files = {
'file': ('Hello world! This is a test!'),
}
然后就可以发起上传请求,注意在这里需要添加代理的参数
response = requests.post(add_url, files=files, proxies=proxies, timeout=5)
p = response.json()
hash = p['Hash']
print(hash)
正常情况下,上面代码执行完,就能看到一个返回的Hash值,也就是刚才上传到IPFS的文件的CID。
接下来我们可以使用这个CID从IPFS网络上查阅一下它的内容。
params = (
('arg', hash),
)
get_url = 'https://ipfs.infura.io:5001/api/v0/block/get'
response = requests.post(get_url, params=params, proxies=proxies)
print(response.text)
上面这段代码执行完,就会看到我们刚才保存到IPFS的那段话:
Hello world! This is a test!
如果想在浏览器端查看这段话,可以通过 https://ipfs.io/ipfs/QmT9auLVqK2cCNooBSGGreShw7qvaTPS7PvkpmFPsf6Rxy 这个链接直接打开。
如果是要上传某个指定的文件,需要修改files部分的代码为:
files = {
'file': open(r'./rocket.png', mode='rb'),
}
本文完整代码如下:
import requests
import json
proxies = {
"http": "socks5://127.0.0.1:10808",
"https": "socks5://127.0.0.1:10808",
}
add_url = 'https://ipfs.infura.io:5001/api/v0/add'
files = {
'file': ('Hello world! This is a test!'),
}
response = requests.post(add_url, files=files, proxies=proxies, timeout=5)
p = response.json()
hash = p['Hash']
print(hash)
params = (
('arg', hash),
)
get_url = 'https://ipfs.infura.io:5001/api/v0/block/get'
response = requests.post(get_url, params=params, proxies=proxies)
print(response.text)