You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python调用Pinata API 实现本地目录Pinning到IPFS

问题根源

你的三个写法都踩了Pinata上传目录的规则和requests库文件传参的坑:

  1. 前两种写法把多个文件元组嵌套在字典的file键对应的列表里,不符合requests库files参数的格式要求,导致类型解析报错。
  2. 第三种写法虽然参数格式对,但你把所有文件的路径都改成了根目录下的文件名(比如0.png而非images/0.png),Pinata无法识别这些文件属于同一个目录,会判定你上传了多个独立文件,触发报错。

实现说明

上传整个目录的核心是要保留每个文件相对于你要上传的根目录的层级路径,Pinata会自动根据路径把文件组织成目录结构,识别为单个目录上传。requests的files参数要传元组列表,每个元素格式为("file", (文件相对路径, 打开的文件对象))。


完整可运行代码

import os
import requests
import typing as tp

def get_all_files(directory: str) -> tp.List[tp.Tuple[str, str]]:
    """返回(绝对路径,相对路径)的元组列表,相对路径保留目录层级"""
    root_abs = os.path.abspath(directory)
    # 取根目录的上级作为基准计算相对路径,保证上传后父目录名称和本地一致
    base_abs = os.path.dirname(root_abs)
    paths = []
    for root, _, files_ in os.walk(root_abs):
        for file in files_:
            abs_path = os.path.join(root, file)
            rel_path = os.path.relpath(abs_path, base_abs)
            # 统一用正斜杠,避免Windows路径问题
            rel_path = rel_path.replace("\\", "/")
            paths.append((abs_path, rel_path))
    return paths

if __name__ == "__main__":
    # 要上传的本地目录
    upload_dir = "images"
    all_files = get_all_files(upload_dir)
    
    # 构造符合要求的files参数
    files = []
    for abs_path, rel_path in all_files:
        files.append(("file", (rel_path, open(abs_path, "rb"))))
    
    headers = {
        'pinata_api_key': "替换为你自己的pinata_api_key",
        'pinata_secret_api_key': "替换为你自己的pinata_secret_api_key"
    }

    ipfs_url = "https://api.pinata.cloud/pinning/pinFileToIPFS"
    # 如需自定义上传后目录显示名称,可增加data参数:
    # response = requests.post(url=ipfs_url, files=files, headers=headers, data={"pinataMetadata": {"name": "自定义目录名"}})
    response = requests.post(url=ipfs_url, files=files, headers=headers)
    print(response.json())
    
    # 关闭打开的文件句柄
    for f in files:
        f[1][1].close()

内容的提问来源于stack exchange,提问作者Tamás Szabadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:36:04