使用 Vue、Python 和 Flask 进行区块链
来源:dev.to
时间:2024-10-27 11:46:07 357浏览 收藏
欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《使用 Vue、Python 和 Flask 进行区块链》,这篇文章主要讲到等等知识,如果你对文章相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!
使用 vue.js 前端和 python 后端创建完整的区块链应用程序。
让我们概述基本组件并提供一些示例代码片段来帮助您入门。
概述
- 1.后端(python 与 flask) 创建一个简单的区块链结构。 设置 flask api 与区块链交互。
- 2.前端 (vue.js)
- 创建一个与 flask api 通信的 vue.js 应用程序。
- 显示区块链数据并允许用户交互(例如添加新块)。 第 1 步:设置后端
- 安装 flask:确保已安装 flask。您可以使用 pip 来执行此操作:
设置环境
pip install flask
- 创建一个基本的区块链类:
# blockchain.py import hashlib import json from time import time from flask import flask, jsonify, request class blockchain: def __init__(self): self.chain = [] self.current_transactions = [] self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=none): block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount): self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @staticmethod def hash(block): block_string = json.dumps(block, sort_keys=true).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): return self.chain[-1] app = flask(__name__) blockchain = blockchain() @app.route('/mine', methods=['post']) def mine(): values = request.get_json() required = ['proof', 'sender', 'recipient'] if not all(k in values for k in required): return 'missing values', 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) blockchain.new_block(values['proof']) response = { 'message': f'new block forged', 'index': index, 'block': blockchain.last_block, } return jsonify(response), 200 @app.route('/chain', methods=['get']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain), } return jsonify(response), 200 if __name__ == '__main__': app.run(debug=true)
第 2 步:设置前端
- 创建 vue.js 应用程序:如果您尚未创建 vue.js 项目,您可以使用 vue cli 来创建:
vue create my-blockchain-app
- 安装 axios 进行 api 调用:
npm install axios
- 创建一个简单的组件:
// src/components/blockchain.vueblockchain
- block #{{ block.index }} - {{ block.timestamp }}
第三步:将它们放在一起
运行 flask 后端:确保您的 python 服务器正在运行:
python blockchain.py
运行 vue.js 前端:现在,运行您的 vue.js 应用程序:
npm run serve
让我们通过添加更多高级功能来增强区块链应用程序,例如:
- 工作量证明机制:实现基本的工作量证明算法。
- 交易池:允许用户创建交易并在挖矿之前在池中查看它们。 -节点发现:允许多个节点连接并共享区块链。 -改进的前端:创建更具交互性的用户界面来显示区块链和交易。 第 1 步:增强后端
- 更新区块链类 我们将实现基本的工作量证明算法和交易池。
# blockchain.py import hashlib import json from time import time from flask import flask, jsonify, request from urllib.parse import urlparse import requests class blockchain: def __init__(self): self.chain = [] self.current_transactions = [] self.nodes = set() self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=none): block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount): self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @staticmethod def hash(block): block_string = json.dumps(block, sort_keys=true).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): return self.chain[-1] def proof_of_work(self, last_proof): proof = 0 while not self.valid_proof(last_proof, proof): proof += 1 return proof @staticmethod def valid_proof(last_proof, proof): guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000" # adjust difficulty here def register_node(self, address): parsed_url = urlparse(address) self.nodes.add(parsed_url.netloc) def resolve_conflicts(self): neighbours = self.nodes new_chain = none max_length = len(self.chain) for node in neighbours: response = requests.get(f'http://{node}/chain') if response.status_code == 200: length = response.json()['length'] chain = response.json()['chain'] if length > max_length and self.valid_chain(chain): max_length = length new_chain = chain if new_chain: self.chain = new_chain return true return false def valid_chain(self, chain): last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] if block['previous_hash'] != self.hash(last_block): return false if not self.valid_proof(last_block['proof'], block['proof']): return false last_block = block current_index += 1 return true app = flask(__name__) blockchain = blockchain() @app.route('/mine', methods=['post']) def mine(): values = request.get_json() required = ['sender', 'recipient'] if not all(k in values for k in required): return 'missing values', 400 last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) blockchain.new_transaction(sender=values['sender'], recipient=values['recipient'], amount=1) previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash) response = { 'message': 'new block forged', 'index': block['index'], 'block': block, } return jsonify(response), 200 @app.route('/transactions/new', methods=['post']) def new_transaction(): values = request.get_json() required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'missing values', 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'transaction will be added to block {index}'} return jsonify(response), 201 @app.route('/chain', methods=['get']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain), } return jsonify(response), 200 @app.route('/nodes/register', methods=['post']) def register_nodes(): values = request.get_json() nodes = values.get('nodes') if nodes is none: return 'error: please supply a valid list of nodes', 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'new nodes have been added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201 @app.route('/nodes/resolve', methods=['get']) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'our chain was replaced', 'new_chain': blockchain.chain, } else: response = { 'message': 'our chain is authoritative', 'chain': blockchain.chain, } return jsonify(response), 200 if __name__ == '__main__': app.run(debug=true)
第 2 步:增强前端
- 在 vue.js 中创建交易表单 我们现在将创建一个表单供用户提交交易。
// src/components/blockchain.vueblockchain
transactions
blockchain
- block #{{ block.index }} - {{ block.timestamp }}
- {{ transaction.sender }} -> {{ transaction.recipient }}: {{ transaction.amount }}
第三步:节点发现和共识
您可以通过在不同端口上运行 flask 应用程序的多个实例来测试具有多个节点的区块链。例如,您可以运行:
flask_run_port=5001 python blockchain.py
然后,您可以使用 post 请求注册节点:
curl -X POST -H "Content-Type: application/json" -d '{"nodes": ["localhost:5001"]}' http://localhost:5000/nodes/register
这个更先进的区块链应用程序包括:
-工作量证明:挖掘新区块的基本机制。
-交易池:用户可以在交易被开采之前创建交易。
-节点发现:支持多个节点和共识机制。
-交互式前端:用于提交交易和查看区块链的 vue.js ui。
编码愉快!
本篇关于《使用 Vue、Python 和 Flask 进行区块链》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
477 收藏
-
394 收藏
-
132 收藏
-
319 收藏
-
225 收藏
-
294 收藏
-
148 收藏
-
243 收藏
-
176 收藏
-
220 收藏
-
163 收藏
-
361 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习