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')

 

以上!

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