Python区块链浏览器教程:Flask+Web3.py实战
想要用Python打造专属的区块链浏览器吗?本文将手把手教你使用Flask和Web3.py库,从零开始构建一个简易但功能完备的区块链数据查询工具。首先,我们将安装必要的库,并通过Web3.py连接到以太坊节点,例如Infura或本地Ganache。接着,利用Flask框架创建路由,分别展示最新区块信息、区块详情、交易详情以及地址信息。通过Jinja2模板引擎,将这些数据渲染成美观的前端页面。更进一步,我们还将实现搜索功能,方便用户快速定位到目标区块、交易或地址。最终,你将拥有一个可运行的Python区块链浏览器,轻松探索链上数据。
用Python制作区块链浏览器的核心是结合Flask和Web3.py库,1. 安装Flask和web3库;2. 使用Web3.py连接以太坊节点(如Infura或本地Ganache);3. 通过Flask创建路由展示最新区块、区块详情、交易详情和地址信息;4. 利用Jinja2模板渲染前端页面;5. 实现搜索功能跳转至对应数据页面;最终实现一个可查询区块链数据的简易浏览器,完整且可运行。

用Python制作一个区块链浏览器,核心在于巧妙结合Flask这个轻量级Web框架和Web3.py库,后者是Python与以太坊区块链交互的强大桥梁。这套组合能让你从零开始,搭建一个能查看区块、交易和地址信息的简易版浏览器。说起来,这事儿比想象中要“接地气”,并非高不可攀,更多是数据获取与前端展示的串联。
解决方案
要动手干这事儿,我们得先搭好架子。Flask负责骨架,Web3.py负责血肉,它们俩得配合得天衣无缝。
首先,确保你的Python环境准备妥当,然后安装必要的库:
pip install Flask web3
接下来,我们来构建核心逻辑。一个简单的Flask应用,它会连接到以太坊节点,并尝试获取最新的区块信息。
1. 后端核心 (app.py)
from flask import Flask, render_template, request, redirect, url_for
from web3 import Web3
from web3.exceptions import Web3Exception # 引入异常处理
app = Flask(__name__)
# 连接到以太坊节点
# 推荐使用Infura、Alchemy等服务,它们提供稳定的API接口
# 记得替换 YOUR_INFURA_PROJECT_ID 为你自己的项目ID
# infura_url = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"
# w3 = Web3(Web3.HTTPProvider(infura_url))
# 开发测试时,也可以连接本地Ganache或Geth节点
# w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545')) # Ganache默认端口
# 确保连接成功,如果连接失败,这里会抛出异常或返回False
try:
# 尝试连接到Infura公共节点,如果你的Infura ID是空的,这里会失败
# 也可以直接用一个公共的测试网节点,例如 Goerli
w3 = Web3(Web3.HTTPProvider('https://goerli.infura.io/v3/YOUR_INFURA_PROJECT_ID'))
if not w3.is_connected():
print("警告:未能连接到以太坊节点,请检查网络或Infura ID。")
w3 = None # 设置为None,后续逻辑会处理
except Web3Exception as e:
print(f"连接Web3时发生错误: {e}")
w3 = None
@app.route('/')
def index():
if not w3 or not w3.is_connected():
return "未能连接到区块链网络,请检查后端服务配置或网络连接。", 500
try:
latest_block_number = w3.eth.block_number
latest_block = w3.eth.get_block(latest_block_number)
# 简化处理,只传递部分信息给模板
block_info = {
'number': latest_block.number,
'hash': latest_block.hash.hex(),
'timestamp': latest_block.timestamp,
'transactions_count': len(latest_block.transactions),
'miner': latest_block.miner,
'gas_used': latest_block.gasUsed,
'gas_limit': latest_block.gasLimit,
'parent_hash': latest_block.parentHash.hex()
}
return render_template('index.html', block=block_info)
except Exception as e:
return f"获取最新区块信息失败: {e}", 500
@app.route('/block/<int:block_number>')
def get_block_details(block_number):
if not w3 or not w3.is_connected():
return "未能连接到区块链网络。", 500
try:
block = w3.eth.get_block(block_number, full_transactions=False) # full_transactions=False 减少数据量
if not block:
return "区块未找到。", 404
block_info = {
'number': block.number,
'hash': block.hash.hex(),
'timestamp': block.timestamp,
'transactions_count': len(block.transactions),
'miner': block.miner,
'gas_used': block.gasUsed,
'gas_limit': block.gasLimit,
'parent_hash': block.parentHash.hex(),
'transactions': [tx.hex() for tx in block.transactions] # 只显示交易哈希
}
return render_template('block_details.html', block=block_info)
except Exception as e:
return f"获取区块 {block_number} 详情失败: {e}", 500
@app.route('/tx/<string:tx_hash>')
def get_transaction_details(tx_hash):
if not w3 or not w3.is_connected():
return "未能连接到区块链网络。", 500
try:
# 确保哈希格式正确
if not tx_hash.startswith('0x') or len(tx_hash) != 66:
return "无效的交易哈希格式。", 400
tx = w3.eth.get_transaction(tx_hash)
if not tx:
return "交易未找到。", 404
tx_receipt = w3.eth.get_transaction_receipt(tx_hash) # 获取交易收据以获得状态、gas消耗等
tx_info = {
'hash': tx.hash.hex(),
'block_number': tx.blockNumber,
'from': tx['from'],
'to': tx['to'],
'value': w3.from_wei(tx.value, 'ether'), # 转换为ETH
'gas_price': w3.from_wei(tx.gasPrice, 'gwei'), # 转换为Gwei
'gas_limit': tx.gas,
'nonce': tx.nonce,
'input': tx.input, # 智能合约调用数据
'status': '成功' if tx_receipt and tx_receipt.status == 1 else '失败',
'gas_used': tx_receipt.gasUsed if tx_receipt else 'N/A'
}
return render_template('transaction_details.html', tx=tx_info)
except Exception as e:
return f"获取交易 {tx_hash} 详情失败: {e}", 500
@app.route('/address/<string:address>')
def get_address_details(address):
if not w3 or not w3.is_connected():
return "未能连接到区块链网络。", 500
try:
# 确保地址格式正确
if not w3.is_address(address):
return "无效的以太坊地址格式。", 400
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.from_wei(balance_wei, 'ether')
# 简单展示,不获取所有交易(这会非常慢且消耗资源)
# 实际项目中,需要通过第三方API或索引服务获取地址交易历史
address_info = {
'address': address,
'balance': balance_eth
}
return render_template('address_details.html', address=address_info)
except Exception as e:
return f"获取地址 {address} 详情失败: {e}", 500
# 搜索功能
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('query', '').strip()
if not query:
return redirect(url_for('index'))
# 尝试作为区块号
if query.isdigit():
return redirect(url_for('get_block_details', block_number=int(query)))
# 尝试作为交易哈希
elif query.startswith('0x') and len(query) == 66:
return redirect(url_for('get_transaction_details', tx_hash=query))
# 尝试作为地址
elif query.startswith('0x') and len(query) == 42: # 以太坊地址长度
return redirect(url_for('get_address_details', address=query))
else:
return "未识别的查询类型(请输入区块号、交易哈希或地址)。", 400
if __name__ == '__main__':
app.run(debug=True)2. 前端模板 (templates/index.html, block_details.html, transaction_details.html, address_details.html)
在项目根目录下创建templates文件夹,并放入以下HTML文件。
templates/base.html (基础布局,方便复用)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}简易区块链浏览器{% endblock %}</title>
<style>
body { font-family: sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
.container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
h1, h2 { color: #007bff; }
.data-item { margin-bottom: 10px; border-bottom: 1px dashed #eee; padding-bottom: 5px; }
.data-item strong { display: inline-block; width: 120px; color: #555; }
a { color: #007bff; text-decoration: none; }
a:hover { text-decoration: underline; }
.search-box { margin-bottom: 20px; padding: 15px; background-color: #e9ecef; border-radius: 5px; display: flex; align-items: center; }
.search-box input[type="text"] { flex-grow: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px; margin-right: 10px; }
.search-box button { padding: 8px 15px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; }
.search-box button:hover { background-color: #218838; }
.error-message { color: red; font-weight: bold; }
</style>
</head>
<body>
<div class="container">
<header>
<h1><a href="/">简易区块链浏览器</a></h1>
<div class="search-box">
<form action="/search" method="GET" style="display: flex; width: 100%;">
<input type="text" name="query" placeholder="搜索区块号 / 交易哈希 / 地址" size="50">
<button type="submit">搜索</button>
</form>
</div>
</header>
<main>
{% block content %}{% endblock %}
</main>
</div>
</body>
</html>templates/index.html (首页)
{% extends "base.html" %}
{% block title %}最新区块 - 简易区块链浏览器{% endblock %}
{% block content %}
<h2>最新区块信息</h2>
{% if block %}
<div class="data-item"><strong>区块号:</strong> <a href="{{ url_for('get_block_details', block_number=block.number) }}">{{ block.number }}</a></div>
<div class="data-item"><strong>哈希:</strong> {{ block.hash }}</div>
<div class="data-item"><strong>时间戳:</strong> {{ block.timestamp | int | timestamp_to_datetime }}</div>
<div class="data-item"><strong>交易数量:</strong> {{ block.transactions_count }}</div>
<div class="data-item"><strong>矿工:</strong> <a href="{{ url_for('get_address_details', address=block.miner) }}">{{ block.miner }}</a></div>
<div class="data-item"><strong>Gas使用量:</strong> {{ block.gas_used }}</div>
<div class="data-item"><strong>Gas限制:</strong> {{ block.gas_limit }}</div>
<div class="data-item"><strong>父区块哈希:</strong> {{ block.parent_hash }}</div>
{% else %}
<p class="error-message">未能加载区块信息。</p>
{% endif %}
<script>
// 简单的过滤器,将Unix时间戳转换为可读日期
// 在实际Flask应用中,你可能需要在Python后端处理或使用Jinja2的过滤器
// 这里只是一个前端的简单示例,实际需要后端处理或更复杂的JS库
if (typeof Jinja2 === 'undefined') { // 避免重复定义
var Jinja2 = {};
Jinja2.filters = {
timestamp_to_datetime: function(timestamp) {
const date = new Date(timestamp * 1000);
return date.toLocaleString();
}
};
}
// 为了让Jinja2过滤器在HTML中生效,通常需要在Python后端注册
// 例如:app.jinja_env.filters['timestamp_to_datetime'] = lambda ts: datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
</script>
{% endblock %}**注意:
好了,本文到此结束,带大家了解了《Python区块链浏览器教程:Flask+Web3.py实战》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!
Go语言别名与方法继承详解
- 上一篇
- Go语言别名与方法继承详解
- 下一篇
- PhpStorm必备10个高效开发插件推荐
-
- 文章 · python教程 | 3小时前 |
- Python语言入门与基础解析
- 296浏览 收藏
-
- 文章 · python教程 | 3小时前 |
- PyMongo导入CSV:类型转换技巧详解
- 351浏览 收藏
-
- 文章 · python教程 | 3小时前 |
- Python列表优势与实用技巧
- 157浏览 收藏
-
- 文章 · python教程 | 3小时前 |
- Pandas修改首行数据技巧分享
- 485浏览 收藏
-
- 文章 · python教程 | 5小时前 |
- Python列表创建技巧全解析
- 283浏览 收藏
-
- 文章 · python教程 | 5小时前 |
- Python计算文件实际占用空间技巧
- 349浏览 收藏
-
- 文章 · python教程 | 6小时前 |
- OpenCV中OCR技术应用详解
- 204浏览 收藏
-
- 文章 · python教程 | 7小时前 |
- Pandas读取Django表格:协议关键作用
- 401浏览 收藏
-
- 文章 · python教程 | 7小时前 | 身份验证 断点续传 requests库 PythonAPI下载 urllib库
- Python调用API下载文件方法
- 227浏览 收藏
-
- 文章 · python教程 | 8小时前 |
- Windows7安装RtMidi失败解决办法
- 400浏览 收藏
-
- 文章 · python教程 | 8小时前 |
- Python异步任务优化技巧分享
- 327浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3180次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3391次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3420次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4526次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3800次使用
-
- Flask框架安装技巧:让你的开发更高效
- 2024-01-03 501浏览
-
- Django框架中的并发处理技巧
- 2024-01-22 501浏览
-
- 提升Python包下载速度的方法——正确配置pip的国内源
- 2024-01-17 501浏览
-
- Python与C++:哪个编程语言更适合初学者?
- 2024-03-25 501浏览
-
- 品牌建设技巧
- 2024-04-06 501浏览

