Python API实现IPFS的文件上传、下载功能

由于IPFS提供的SDK只有go和js的,但实际应用中使用的Python开发,于是想到使用http请求来实现,go-ipfs内置了API请求接口,地址为:

API server listening on /ip4/127.0.0.1/tcp/5001

即:

http://127.0.0.1:5001

参考 官方文档 翻译文档  CURL 请求参数

实现了上传单文本功能:

     

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

import requests

if __name__ == '__main__':
    host = "http://127.0.0.1:5001"
    url_upload = host + "/api/v0/add"

    files = {
        'file': open(r"D:\Project\segtag\requirements.txt", mode='rb')
    }
    response = requests.post(url_upload, files=files)
    if response.status_code == 200:
        print('上传成功!')
        data = json.loads(response.text)
        hash_code = data['Hash']

    else:
        hash_code = None

    # 下载
    if hash_code:
        url_download = host + "/api/v0/cat"
        params = {
            'arg': hash_code
        }
        response = requests.post(url_download, params=params)
        print(response.text)

 

emmm,写完之后思考了一下,要不要将所有的接口封装成一个包,方便以后使用,然后想了下,这种包在GitHub上是否已经存在了?于是乎,去搜索

果然如此,附链接:py-ipfs-http-client

截止到2020519日,此客户端暂不支持go-ipfs 0.4.18及以下版本、 v0.5.0及以上版本(PS:最新版本为 0.5.1 ),并且版本限制在如图所示:

GitHub 此项目readme截图:

期待后续更新,所以这次还是自己实现各种不同的API。

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

import requests


class IPFSApiClient:
    def __init__(self, host="http://127.0.0.1:5001"):
        self.__host = host
        self.__upload_url = self.__host + "/api/v0/add"
        self.__cat_url = self.__host + "/api/v0/cat"
        self.__version_url = self.__host + "/api/v0/version"
        self.__options_request()

    def __options_request(self):
        """
        测试请求是否可以连通
        :return:
        """
        try:
            requests.post(self.__version_url, timeout=10)
        except requests.exceptions.ConnectTimeout:
            raise SystemExit("连接超时,请确保已开启 IPFS 服务")
        except requests.exceptions.ConnectionError:
            raise SystemExit("无法连接至 %s " % self.__host)

    def upload_file(self, file_path):
        """

        :param file_path: 上传文件路径
        :return: 文件的hash code编码
        """
        try:
            file = open(file_path, mode='rb')
        except FileNotFoundError:
            raise FileExistsError("文件不存在!")

        files = {
            'file': file
        }
        response = requests.post(self.__upload_url, files=files)
        if response.status_code == 200:
            data = json.loads(response.text)
            hash_code = data['Hash']
        else:
            hash_code = None

        return hash_code

    def cat_hash(self, hash_code):
        """
        读取文件内容
        :param hash_code:
        :return:
        """
        params = {
            'arg': hash_code
        }
        response = requests.post(self.__cat_url, params=params)
        if response.status_code == 200:
            return response.text.decode("utf-8")
        else:
            return "未获取到数据!"

    def download_hash(self, hash_code, save_path):
        """
        读取文件内容
        :param hash_code:
        :param save_path:  文件保存路径
        :return:
        """
        params = {
            'arg': hash_code
        }
        response = requests.post(self.__cat_url, params=params)
        if response.status_code == 200:
            with open(save_path, mode='wb') as f:
                f.write(response.content)
            return True, '保存成功'
        else:
            return False, "未获取到数据!"


if __name__ == '__main__':
    client = IPFSApiClient()
    client.download_hash('QmbTiKz43BJPGtXc5hXAQrQeQetU6Ku63vB1SZA7cZS9yA', 'test.zip')

 

以上!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章