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语言别名与方法继承详解

- 下一篇
- PhpStorm必备10个高效开发插件推荐
-
- 文章 · python教程 | 11秒前 |
- 计算字典键值总和的Python方法
- 439浏览 收藏
-
- 文章 · python教程 | 5分钟前 |
- Python操作HBase实战教程
- 455浏览 收藏
-
- 文章 · python教程 | 26分钟前 |
- FastAPI开发教程:快速搭建API接口
- 482浏览 收藏
-
- 文章 · python教程 | 35分钟前 | Python 数据冲突 Riak riak-python-client 二级索引
- Python操作Riak教程:riak-python-client使用指南
- 161浏览 收藏
-
- 文章 · python教程 | 42分钟前 |
- Python设置Excel字体颜色教程
- 482浏览 收藏
-
- 文章 · python教程 | 42分钟前 |
- PyCharm中文界面设置教程3步搞定
- 215浏览 收藏
-
- 文章 · python教程 | 43分钟前 |
- Python操作Word文档的实用技巧
- 202浏览 收藏
-
- 文章 · python教程 | 45分钟前 |
- PyCharm安装教程图文详细步骤
- 153浏览 收藏
-
- 文章 · python教程 | 54分钟前 |
- Pythonitertools排列与字符差异分析
- 377浏览 收藏
-
- 文章 · python教程 | 1小时前 |
- AWSLambda冷启动影响运行时长吗?真相揭秘
- 205浏览 收藏
-
- 文章 · python教程 | 1小时前 |
- Python处理LIDAR数据与点云可视化技巧
- 101浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 151次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 143次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 157次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 150次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 159次使用
-
- 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浏览