通过 Horizon 查询数据

通过 Stellar Python SDK 你可以访问 Horizon 的各个接口。

构建请求

SDK 使用 建造者模式 来创建请求。通过 Server ,我们可以链式的构建一个请求。 (请参阅 Horizon 文档 来了解有哪些方法是可用的。)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from stellar_sdk import Server

server = Server(horizon_url="https://horizon-testnet.stellar.org")

# get a list of transactions that occurred in ledger 1400
transactions = server.transactions().for_ledger(1400).call()
print(transactions)

# get a list of transactions submitted by a particular account
transactions = server.transactions() \
    .for_account(account_id="GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW") \
    .call()
print(transactions)

当请求构建完成之后,我们可以通过调用 call() 以向 Horizon 发起请求。 call() 将会立即返回一个响应。

构建流式(Stream)请求

很多接口都能通过 stream() 调用。 与 call() 不同,它不立刻返回结果, 而是会返回一个 EventSource。

Horizon 将会实时的返回从当前时间开始产生的数据,当然你也可以通过 cursor() 指定一个时间点。 (请参阅 Horizon 文档 了解有哪些接口支持 Stream。)

下面这个示例将会实时打印这个账户提交的事务。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from stellar_sdk import Server

server = Server(horizon_url="https://horizon-testnet.stellar.org")
account_id = "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW"
last_cursor = 'now'  # or load where you left off


def tx_handler(tx_response):
    print(tx_response)


for tx in server.transactions().for_account(account_id).cursor(last_cursor).stream():
    tx_handler(tx)