首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python中的脚本将包含元数据的文件夹上传到pinata?

如何使用python中的脚本将包含元数据的文件夹上传到pinata?
EN

Stack Overflow用户
提问于 2022-11-07 17:00:37
回答 1查看 31关注 0票数 0

过去24小时我一直在努力,但一直找不到解决办法。这是代码:

代码语言:javascript
复制
import os
from pathlib import Path
import requests

PINATA_BASE_URL = "https://api.pinata.cloud/"
endpoint = "pinning/pinFileToIPFS"
# Change this filepath
filepath = "C:/Users/acer/Desktop/Ciao"
filename = os.listdir(filepath)
print(filename)
headers = {
    "pinata_api_key": os.getenv("PINATA_API_KEY"),
    "pinata_secret_api_key": os.getenv("PINATA_API_SECRET"),
}


def main():
    with Path(filepath).open("rb") as fp:
        image_binary = filepath.read()
        print(image_binary)
        response = requests.post(
            PINATA_BASE_URL + endpoint,
            files={"file": (filename, image_binary)},
            headers=headers,
        )
        print(response.json())


if __name__ == "__main__":
    main()

我试图打开存储元数据的文件夹,并将请求与文件夹中的文件列表一起发送。这是一个错误:

代码语言:javascript
复制
['no.txt', 'yeah.txt']
Traceback (most recent call last):
  File "C:\Users\acer\Desktop\SOLIDITY_PYTHON\nft-bored-ape\scripts\upload_to_pinata.py", line 30, in <module>
    main()
  File "C:\Users\acer\Desktop\SOLIDITY_PYTHON\nft-bored-ape\scripts\upload_to_pinata.py", line 18, in main    
    with Path(filepath).open("rb") as fp:
  File "C:\Users\acer\AppData\Local\Programs\Python\Python310\lib\pathlib.py", line 1119, in open
    return self._accessor.open(self, mode, buffering, encoding, errors,
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\acer\\Desktop\\Ciao'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-08 17:51:20

不介意..。经过一番研究,我找到了我自己问题的答案。以下是代码:

代码语言:javascript
复制
# Tulli's script :-)
from brownie import config
import requests, os, typing as tp


PINATA_BASE_URL = "https://api.pinata.cloud/"
endpoint = "pinning/pinFileToIPFS"
# Here you could use os.getenv("VARIABLE_NAME"),
# i used config from my .yaml file. Your choice!
headers = {
    "pinata_api_key": config["pinata"]["api-keys"],
    "pinata_secret_api_key": config["pinata"]["api-private"],
}


def get_all_files(directory: str) -> tp.List[str]:
    """get a list of absolute paths to every file located in the directory"""
    paths: tp.List[str] = []
    for root, dirs, files_ in os.walk(os.path.abspath(directory)):
        for file in files_:
            paths.append(os.path.join(root, file))
    return paths


def upload_folder_to_pinata(filepath):
    all_files: tp.List[str] = get_all_files(filepath)
    # The replace function is a must, 
    # pinata servers doesn't recognize the backslash. 
    # Your filepath is probably different than mine,
    # so in the split function put your "penultimate_file/".
    # Strip the square brackets and the apostrophe,
    # because we don't want it as part of the metadata ipfs name
    files = [
        (
            "file",
            (
                str(file.replace("\\", "/").split("Desktop/")[-1:])
                .strip("[]")
                .strip("'"),
                open(file, "rb"),
            ),
        )
        for file in all_files
    ]
    response: requests.Response = requests.post(
        PINATA_BASE_URL + endpoint,
        files=files,
        headers=headers,
    )
    # If you want to see all the stats then do this: 
    # return/print/do both separately response.json()
    return "ipfs.io/ipfs/" + response.json()["IpfsHash"]


def main():
    upload_folder_to_pinata("Put your full filepath here")


if __name__ == "__main__":
    main()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74350228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档