Python SDK
Python SDK 可让你连接、探索并与 Aptos 区块链交互。你可以用它请求数据、发送交易、设置测试环境等。
安装 Python SDK
Section titled “安装 Python SDK”Aptos 在 PyPI 上提供官方 Python SDK,源代码位于 aptos-python-sdk GitHub 仓库。 该 SDK 需要 Python 3.12+。
使用 pip 安装:
pip install aptos-sdk或从源代码安装:
git clone https://github.com/aptos-labs/aptos-python-sdkcd aptos-python-sdkpip install . 快速入门 几分钟内在 Devnet 上完成一笔可运行的转账
账户 生成、恢复并为账户注资
获取数据 读取账本、账户和 View 函数数据
提交交易 构建、模拟、签名并提交交易
示例 SDK 仓库中的可运行示例目录
测试 覆盖 v2 API 的单元测试和集成测试
来自已测试示例套件的 APT 转账
Section titled “来自已测试示例套件的 APT 转账”以下片段取自 SDK 仓库中的
v2/examples/transfer_apt.py。
从 PyPI 安装时,请从 aptos_sdk.v2 导入相同 API,而不是 aptos_sdk_v2。
30 collapsed lines
"""Example: Transfer APT between accounts on devnet."""
import asyncio
from aptos_sdk_v2 import Account, Aptos, AptosConfig, Network
async def main(): config = AptosConfig(network=Network.DEVNET) async with Aptos(config) as aptos: # Create two accounts alice = Account.generate() bob = Account.generate() print(f"Alice: {alice.address}") print(f"Bob: {bob.address}")
# Fund Alice print("\nFunding Alice...") await aptos.faucet.fund_account(alice.address, 100_000_000)
# Fund Bob so account exists on-chain print("Funding Bob...") await aptos.faucet.fund_account(bob.address, 10_000_000)
# Check balances alice_balance = await aptos.coin.balance(alice.address) bob_balance = await aptos.coin.balance(bob.address) print(f"\nAlice balance: {alice_balance}") print(f"Bob balance: {bob_balance}")
# Transfer 1000 octas from Alice to Bob print("\nTransferring 1000 octas from Alice to Bob...") txn_hash = await aptos.coin.transfer(alice, bob.address, 1_000) result = await aptos.transaction.wait_for_transaction(txn_hash) print(f"Transaction: {txn_hash}") print(f"Success: {result['success']}")10 collapsed lines
# Check final balances alice_balance = await aptos.coin.balance(alice.address) bob_balance = await aptos.coin.balance(bob.address) print(f"\nAlice balance: {alice_balance}") print(f"Bob balance: {bob_balance}")
if __name__ == "__main__": asyncio.run(main())