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

Python中对Pi测试网API交易数据分组及URL参数解析

Pi测试网交易数据获取与格式化方案

一、API参数解析

你提到的{?cursor,limit,order}是API的查询参数,具体含义:

  • cursor:分页标记,用于获取下一批数据。首次请求可省略,后续若需加载更多,使用返回结果中_links.next.href里的cursor值即可
  • limit:单次请求返回的交易条数上限,最大值为200,要获取55笔直接设为55
  • order:交易排序规则,asc按交易时间升序排列,desc按降序排列

二、修正后的代码实现

原代码的URL参数格式错误,需改为键值对形式;同时要对返回的交易数据进行分组统计,代码如下:

import requests

# 请求头
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:104.0) Gecko/20100101 Firefox/104.0'}
# 目标账户地址
account_id = "GCMWJ5FHNS6VFMIY34IL55YCQEJCGWYWUBKDRAEA3KS7DHRIPRA37P7D"
# 构造正确的请求URL,获取55笔升序排列的交易
url = f"https://api.testnet.minepi.com/accounts/{account_id}/payments?limit=55&order=asc"

try:
    # 发送请求并解析JSON
    response = requests.get(url, headers=headers, timeout=10).json()
    payments = response.get('_embedded', {}).get('records', [])
    
    # 初始化统计变量
    outgoing = []
    outgoing_total = 0.0
    incoming = []
    incoming_total = 0.0
    
    # 遍历交易数据,区分出入账
    for payment in payments:
        amount = float(payment['amount'])
        if payment['to'] == account_id:
            # 入账交易
            incoming.append({
                'amount': amount,
                'from': payment['from']
            })
            incoming_total += amount
        else:
            # 出账交易
            outgoing.append({
                'amount': amount,
                'to': payment['to']
            })
            outgoing_total += amount
    
    # 格式化输出出账信息
    print("Outgoing Transactions: ")
    for tx in outgoing:
        print(f"amount: {tx['amount']:>9.7f}     ->  to: {tx['to']}")
    print(f"\nTotal Outgoing: {len(outgoing)}")
    print(f"Total Amount:   {outgoing_total:.7f}\n")
    
    # 格式化输出入账信息
    print("Incoming Transactions: ")
    for tx in incoming:
        print(f"amount: {tx['amount']:>9.7f}    ->  from: '{tx['from']}'")
    print(f"\nTotal Incoming:   {len(incoming)}")
    print(f"Total Amount:   {incoming_total:.7f}")

except Exception as e:
    print(f"请求出错: {str(e)}")

三、输出说明

运行代码后会得到类似你期望的格式化结果:

Outgoing Transactions: 
amount:  5.0000000     ->  to: GA6DJZLKRPWATZVGKZEKBGEX4CHJYBSRNPDBIQ3RUCC3RW3XVL2EZ6XF
amount:  3.0000000     ->  to: GCMWJ5FHNS6VFMIY34IL55YCQEJCGWYWUBKDRAEA3KS7DHRIPRA37P7D

Total Outgoing: 2
Total Amount:   8.0000000

Incoming Transactions: 
amount:  5.1000000    ->  from: 'GD3TTNZ47C4CTJM6A6O7AU7YVQOJN6YEFBYWDKNLCJFOFSXEEPK5WYMN'
amount: 15.0000000    ->  from: 'GD3TTNZ47C4CTJM6A6O7AU7YVQOJN6YEFBYWDKNLCJFOFSXEEPK5WYMN'

Total Incoming:   2
Total Amount:   20.1000000

内容的提问来源于stack exchange,提问作者errzoned

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:55:10