登录
首页 >  文章 >  python教程

Python区块链浏览器教程:Flask+Web3.py实战

时间:2025-08-11 19:18:49 443浏览 收藏

想要用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+Web3.py

用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/')
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/')
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/')
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 (基础布局,方便复用)




    
    
    {% block title %}简易区块链浏览器{% endblock %}
    


    

简易区块链浏览器

{% block content %}{% endblock %}

templates/index.html (首页)

{% extends "base.html" %}

{% block title %}最新区块 - 简易区块链浏览器{% endblock %}

{% block content %}
    

最新区块信息

{% if block %}
哈希: {{ block.hash }}
时间戳: {{ block.timestamp | int | timestamp_to_datetime }}
交易数量: {{ block.transactions_count }}
Gas使用量: {{ block.gas_used }}
Gas限制: {{ block.gas_limit }}
父区块哈希: {{ block.parent_hash }}
{% else %}

未能加载区块信息。

{% endif %} {% endblock %}

**注意:

好了,本文到此结束,带大家了解了《Python区块链浏览器教程:Flask+Web3.py实战》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>