:2026-02-18 9:57 点击:5
以太坊 API Python 编程指南:连接区块链与 Python 应用的桥梁
以太坊作为全球领先的智能合约平台和去中心化应用(DApps)的底层基础设施,其开放性和可编程性吸引了无数开发者和企业,而 Python,以其简洁的语法、丰富的库生态和广泛的应用场景,成为了与以太坊交互的热门选择,通过以太坊 API,Python 开发者可以轻松地读取区块链数据、发送交易、部署智能合约,从而构建强大的去中心化应用或区块链分析工具,本文将深入探讨如何利用 Python 与以太坊 API 进行交互。
以太坊本身并没有直接为 Python 提供官方 API,而是通过一系列标准化的接口(API)暴露其功能,这些 API 主要分为以下几类:

要在 Python 中与以太坊 API 交互,Web3.py 是不可或缺的核心工具,它是一个强大且功能齐全的库,支持与符合以太坊标准的节点进行通信。
你需要通过 pip 安装 Web3.py:
pip install web3
使用 Web3.py 连接到以太坊节点是第一步,你可以连接到本地节点或远程节点(如 Infura)。
from web3 import Web3
# w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
# 连接到 Infura 提供的远程节点(需要替换为你的 Infura 项目 ID)
infura_url = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID'
w3 = Web3(Web3.HTTPProvider(infura_url))
# 检查连接是否成功
if w3.is_connected():
print("成功连接到以太坊节点!")
print(f"当前区块号: {w3.eth.block_number}")
else:
print("连接失败!")
一旦连接成功,你可以轻松读取各种区块链数据:
# 获取最新区块号
latest_block = w3.eth.block_number
print(f"最新区块号: {latest_block}")
# 获取指定区块的信息
block_info = w3.eth.get_block(latest_block)
print(f"区块 {latest_block} 的哈希: {block_info.hash.hex()}")
# 获取账户余额(需要替换为实际地址)
address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e'
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.from_wei(balance_wei, 'ether')
print(f"地址 {address} 的余额: {balance_eth} ETH")
# 获取交易信息(需要替换为实际交易哈希)
tx_hash = '0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060'
tx_info = w3.eth.get_transaction(tx_hash)
print(f"交易 {tx_hash} 的发送方: {tx_info['from']}")
发送交易和与智能合约交互是 Web3.py 更强大的功能。
发送交易:
# 注意:实际发送交易需要私钥,这里仅作示意
# from web3.eth.account import Account
# 假设我们有发送方的私钥和接收方地址
sender_private_key = 'YOUR_PRIVATE_KEY' # 务必妥善保管,不要泄露
receiver_address = '0x1234567890123456789012345678901234567890'
# 创建账户对象
# sender_account = Account.from_key(sender_private_key)
# 获取nonce
nonce = w3.eth.get_transaction_count(sender_account.address)
# 构建交易
tx = {
'nonce': nonce,
'to': receiver_address,
'value': w3.to_wei(0.01, 'ether'), # 发送0.01 ETH
'gas': 200000,
'gasPrice': w3.eth.gas_price,
'chainId': 1 # 主网chainId
}
# 签名交易
# signed_tx = sender_account.sign_transaction(tx)
# 发送交易
# tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
# print(f"交易发送成功,哈希: {tx_hash.hex()}")
# 等待交易确认
# receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# print(f"交易回执: {receipt}")
与智能合约交互: 与智能合约交互需要合约的 ABI(Application Binary Interface,应用程序二进制接口)和字节码(Bytecode),你已经部署好的合约会有 ABI。
# 假设我们有一个简单的存储合约,其ABI如下(简化版)
# 实际使用时需要替换为你的合约完整ABI
contract_abi = [
{
"inputs": [],
"name": "get",
"outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [{"internalType": "uint256", "name": "x", "type": "uint256"}],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
]
# 合约地址(需要替换为实际部署的合约地址)
contract_address = '0xYourContractAddressHere'
# 创建合约实例
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
# 调用合约的view/pure函数(读取数据)
current_value = contract.functions.get().call()
print(f"合约当前存储的值: {current_value}")
# 调用合约的nonpayable/payable函数(修改状态,需要发送交易)
# 注意:这同样需要私钥和gas
# set_tx = contract.functions.set(42).build_transaction({
# 'nonce': nonce + 1, # nonce递增
# 'gas': 200000,
# 'gasPrice': w3.eth.gas_price,
# 'chainId': 1
# })
# signed_set_tx = sender_account.sign_transaction(set_tx)
# set_tx_hash = w3.eth.send_raw_transaction(signed_set_tx.rawTransaction)
# set_receipt = w3.eth.wait_for_transaction_receipt(set_tx_hash)
# print(f"Set交易回执: {set_receipt}")
# 再次调用get函数验证
updated_value = contract.functions.get().call()
print(f"修改后合约存储的值: {updated_value}")
结合以太坊 API 和 Python,可以实现多种有趣的应用:
本文由用户投稿上传,若侵权请提供版权资料并联系删除!