0 u2 ~3 Q" d- f* s4 ?) G2 r
“DApp”代表去中心化应用程序。与传统应用程序一样,去中心化应用程序也有前端(客户端)和后端(服务器端)。DApp 的用户界面可以用任何语言编写(就像传统应用程序一样),并且可以调用其后端。那么,Dapps 与传统应用程序有何不同?DApp 的后端代码运行在分散的对等网络(即区块链)上。您可能听说过 BitTorrent、Tor、Popcorn Time——它们是在点对点网络上运行但不在区块链上运行的 DApp。区块链 DApp 有自己的后端代码,称为智能合约,可以部署到区块链(最常见的是以太坊)。智能合约定义了整个 DApp 的逻辑。它是使用区块链作为后端的命脉。那么Python 开发人员可以在哪里利用它?重点来了——web3。Web3 是一组库,允许您与本地或远程以太坊区块链进行交互。简单地说,web3 是与您的后端(区块链)通信的桥梁。幸运的是,以太坊开发人员已经制作了一个 python 库 web3.py 用于与以太坊进行交互。它的 API 源自 web3 的 JavaScript 版本。因此,除了 web3.js,我们也可以通过 web3.py 库与区块链进行交互。! u% z+ i7 _7 j+ u# i
+ U* _9 m/ |# t7 e! M
Dapps 开发包括三个简单的步骤:% c! Z. L3 Y1 ]& s# E8 [
- 在区块链网络上部署智能合约
- 从部署的智能合约中读取数据
- 将交易发送到部署的智能合约* Y* L) O2 v9 \. O, V+ _
4 e! X0 E2 o: v) p4 A! C% q
安装" v1 v- t# I, s9 T0 n: O5 g
' l3 r! {4 S8 T
Python 2.7 +% E5 I& X! x3 R6 h
Node.js; O: y6 t4 E4 [- P! T$ \
Truffle. K% \) V7 g: ~6 I- @1 K; r8 Y
0 r9 a9 h% k0 Y. V- s& J3 |
npm install -g truffle6 j9 x1 D4 R2 c
Pip
npm i pip
web3.py" c+ P4 N, e* W% C& k
pip install web3: I- [5 |8 B) }- D' }
: T* P/ M# I' e8 K! [
3 F O: }/ Z- F
Infura 项目 API
前往 Infura 网站并注册。创建一个新项目并复制 Ropsten Infura RPC URL。我们将把我们的智能合约部署到 Ropsten 测试网络。% Z' N f C: N
" H) g- _7 U) k. @( B. V
智能合约
0 H3 V. ]8 J* ]
每个程序员都用他们最喜欢的编程语言执行了一个“hello world”程序,以了解运行该语言的基础知识。这是我们使用 Solidity 语言编写的简单的“hello world”版本的智能合约,我们可以在区块链上添加问候语并检索它。Solidity 是编写智能合约最常用的语言,它编译为可以在节点上运行的以太坊虚拟机上执行的字节码。
; c* W6 a9 H d* E: v/ x7 V7 q( g
- pragma solidity ^0.5.7;8 N! @3 u& m: C( m$ X
- contract greeter{* d. m+ h& q: j* R" |
- string greeting;
- function greet(string memory _greeting)public{0 Y% z; o; y( L! u1 e- H
- greeting=_greeting;
- }
- function getGreeting() public view returns(string memory) {
- return greeting;
- }& I' ^; m$ I: r) v
- }
2 C1 S6 O, s, Z, I+ k' S. }' D
您可以通过传递字符串值使用 greet() 方法添加问候语,并使用 getGreting() 方法检索问候语。
1. 在区块链网络上部署智能合约
m6 T# s8 I" i* ~4 Y! F
a) 创建项目:
mkdir pythonDapp6 {8 I1 m7 L% Y/ \4 h
cd pythonDapp
truffle init/ Q1 ]! h9 t, S# a
# O2 c) o& v/ ~' x2 |8 k
成功初始化项目后,转到您的文件夹并在 /contracts目录中创建 greeter.sol 文件。在网络上部署合约之前,我们必须编译它并构建工件。5 L) j) |7 e8 Y' j
b) 智能合约的编译:因此,对于编译,我们将使用 Truffle solc 编译器。在您的主目录中,运行以下命令:. z" Q6 w a) i8 p6 S4 `, h O4 P# h- h
; i: q( J; M. e( Z
truffle compile, M% ^. ~8 ^2 d* z R. j# h C
(or)6 M2 G0 x8 O) ?3 s
truffle.cmd compile #(for windows only)) w3 v* X) U0 I: t
- |* p! \' v+ ^2 z0 r$ m. i
, C2 I8 T9 K8 T/ V! _+ `
上面的命令将在 /contracts 目录中编译你的合约,并在 /build 目录中创建二进制工件文件 greeter.json。
+ S1 d o' g* i1 Q
c) 部署合约:打开您的 Python IDLE 编辑器,并在主目录 deploy.py 中使用以下代码创建一个新文件,然后在您的目录中运行 py deploy.py。
- import json9 q, R4 f% Q: W; ]+ B- O
- from web3 importWeb3, HTTPProvider
- from web3.contract importConciseContract- X! |' E- K; z. ^" e# V
- # web3.py instance- M/ N, n/ |% t# a5 i% @; r
- w3 = Web3(HTTPProvider("https://ropsten.infura.io/v3/<API key>"))
- print(w3.isConnected())
- key="<Private Key here with 0x prefix>"8 r, V6 W& ^+ m8 ^( a# }0 \0 S, ^4 g
- acct = w3.eth.account.privateKeyToAccount(key)
- # compile your smart contract with truffle first) j$ ], c$ p) D
- truffleFile = json.load(open('./build/contracts/greeter.json'))1 f$ u5 ?4 e' ~9 i2 l+ a' v
- abi = truffleFile['abi']- J, ~! v0 I$ S# _8 [8 ~; v) [. L
- bytecode = truffleFile['bytecode']* i" j8 H. g! W8 H9 G" f; C1 ~
- contract= w3.eth.contract(bytecode=bytecode, abi=abi)
- #building transaction# L$ ]3 J/ z9 P$ l5 x' T
- construct_txn = contract.constructor().buildTransaction({
- 'from': acct.address,
- 'nonce': w3.eth.getTransactionCount(acct.address),! d* [2 j3 a/ h( l4 S, S+ o
- 'gas': 1728712,. |% }8 _& _! i5 A- h: @
- 'gasPrice': w3.toWei('21', 'gwei')})
- signed = acct.signTransaction(construct_txn)
- tx_hash=w3.eth.sendRawTransaction(signed.rawTransaction)
- print(tx_hash.hex())
- tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)/ V- u5 b' o; E& Q# f# J9 o4 f% m
- print("Contract Deployed At:", tx_receipt['contractAddress'])
+ G9 z! j: v# ^ ] D* L! Y
这是我所做的:
/ e7 l+ M* o- j' c
导入的 web3 库和所有其他必需的模块0 ~4 \$ e6 e& a; w7 j, O2 r
通过指向 Ropsten Infura 节点启动 web3 提供程序- d Q) [8 w! r+ p) A. b% L
添加了用于签署交易的帐户地址和私钥。不要忘记在代码中添加您的凭据。
通过指向 Truffle 编译的工件文件greeter.json的abi和字节码启动合约实例+ O& T {. j/ A7 `) E
添加了带有随机数、gas、gasPrice 等参数的construct_txn。此处,gas 是指交易应在以太坊中使用和支付的最大计算资源量。gasPrice 是指在交易中使用该数量的 gas 时的最小 Ether 数量。to 指的是您发送交易的地址。仅当您将 Ether 发送到帐户或智能合约时才需要 to 参数。+ p1 j- ?4 @0 A
使用我们的私钥签署交易并在网络上广播。
在控制台中记录交易哈希和部署的合约地址。根据以太坊的说法,事务处理时间 <20 秒。所以你必须等待 20 秒才能获得部署的合约地址。您的后端现在已成功部署在以太坊区块链上。现在您可以使用此地址与您的智能合约进行交互。复制此合约地址。8 F p: A* M, I7 Y, M
2. 向部署的合约发送交易
在我们的合约中,有一个方法greet()。我们可以单独使用这种方法在我们的合同中添加问候语。让我们看看我们如何使用 web3.py 来做到这一点。打开您的 Python IDLE 编辑器并使用以下代码创建一个新文件 sign.py。然后在您的目录中运行 py sign.py。/ G3 F$ G U7 j+ M
- import json
- from web3 importWeb3, HTTPProvider
- from web3.contract importConciseContract
- # compile your smart contract with truffle first* V$ d1 ?1 w) u, k6 u5 f" n+ i) H
- truffleFile = json.load(open('./build/contracts/greeter.json'))
- abi = truffleFile['abi']
- bytecode = truffleFile['bytecode']5 K d( T3 p& A" d. F
- # web3.py instance6 E, A1 C: t' ^
- w3 = Web3(HTTPProvider("https://ropsten.infura.io/v3/<API key>")) #modify
- print(w3.isConnected())( E. N/ Y* @. M1 i3 u. W ?
- contract_address = Web3.toChecksumAddress("<Deployed Contract Address here>") #modify
- key="<Private key with 0x prefix here>"#modify$ F5 u _4 ]# \ a B& }* E( @
- acct = w3.eth.account.privateKeyToAccount(key)
- account_address= acct.address
- # Instantiate and deploy contract+ M" }4 i( _" V
- contract = w3.eth.contract(abi=abi, bytecode=bytecode)* _, k# j: R/ ~2 u
- # Contract instance
- contract_instance = w3.eth.contract(abi=abi, address=contract_address)
- # Contract instance in concise mode$ L. {" {; c! `, @& y" N
- #contract_instance = w3.eth.contract(abi=abi, address=contract_address, ContractFactoryClass=ConciseContract)
- tx = contract_instance.functions.greet("Hello all my goody people").buildTransaction({'nonce': w3.eth.getTransactionCount(account_address)})! o' M. f# z' s5 g+ g# z
- #Get tx receipt to get contract address
- signed_tx = w3.eth.account.signTransaction(tx, key)
- #tx_receipt = w3.eth.getTransactionReceipt(tx_hash)" j: _; e3 V4 i% f
- hash= w3.eth.sendRawTransaction(signed_tx.rawTransaction)! y4 }, b7 z ^; R0 U
- print(hash.hex())
6 M5 x T7 |2 C& Q- d; Z4 N: R0 r
这是我所做的:
导入的 web3 库和所有其他必需的模块; U. I( q* ]% M* u0 d9 S6 [/ Z
通过指向 Ropsten Infura 节点启动 web3 提供程序
添加了用于签署交易的帐户地址和私钥
通过指向 Truffle 编译的工件文件greeter.json的abi和字节码启动合约实例5 _2 R, o) Q0 f/ a: Z- X
创建 tx 对象以添加问候语“hello all my goody people”并建立交易
使用我们的私钥签署交易并在网络上广播。0 @. t6 L4 X' q
在控制台中记录交易哈希。您可以使用您的交易哈希在 etherscan 上检查交易状态。一旦交易被矿工验证,我们的问候语将被添加到区块链上。您可以使用 getGreeting() 函数检索问候语,如下所述。- n4 Z) w$ |; y6 [3 Y: I
3. 从部署的智能合约中读取数据- [6 n, D9 o8 S( X8 M
在我们的合约中,有一个方法 getGreeting() 可以检索我们在区块链中添加的问候语。我们将使用 web3.py 调用此方法 打开您的 Python IDLE 编辑器并使用以下代码创建一个新文件 read.py。运行 py read.py 读取问候语。
- * Z, f7 k; }1 I8 F9 e3 x
- import json
- from web3 importWeb3, HTTPProvider
- from web3.contract importConciseContract) l, D: I8 m* ]- H7 z( v. u6 g
- # compile your smart contract with truffle first
- truffleFile = json.load(open('./build/contracts/greeter.json'))6 I4 ?9 Z. Y$ a
- abi = truffleFile['abi']5 J Y7 C6 w) J
- bytecode = truffleFile['bytecode']2 I! z( l g: G& X
- # web3.py instance+ o0 Z% I) _# F, c+ \% S
- w3 = Web3(HTTPProvider("https://ropsten.infura.io/<ApI Key here>"))
- print(w3.isConnected())
- contract_address = Web3.toChecksumAddress("<Deployed Contract Address here>")
- # Instantiate and deploy contract a/ n [; d7 C5 E5 n# t
- contract = w3.eth.contract(abi=abi, bytecode=bytecode)
- # Contract instance- D! p! D" V, X# W' G. b/ D0 l
- contract_instance = w3.eth.contract(abi=abi, address=contract_address)
- # Contract instance in concise mode
- #contract_instance = w3.eth.contract(abi=abi, address=contract_address, ContractFactoryClass=ConciseContract)# ^5 K7 S, ~% |) ^- l. j
- # Getters + Setters for web3.eth.contract object ConciseContract
- #print(format(contract_instance.getGreeting()))1 j" |" G; y/ i2 D( q4 t
- print('Contract value: {}'.format(contract_instance.functions.getGreeting().call()))
3 K! o4 E/ I. q0 L/ A0 d/ o c
这是我所做的:! c& e- h. ?+ E7 }
0 |4 p2 C) V; s
导入的 web3 库和所有其他必需的模块( M; j( P; k8 g
通过指向 Ropsten Infura 节点启动 web3 提供程序0 V7 a4 S6 @$ B' a9 t- t
通过指向 abi 和 contract_Address 创建合约实例(来自上一步)+ k5 h- G) y, X( o; s1 O3 B
调用 getGreeting() 方法并在控制台打印结果6 n8 u9 b6 x, C. n! y% T# n
结论5 \, x& E% y" l/ r: W9 R" H# y
7 c$ e. S; Z' I$ x* l
您现在应该了解如何使用 web3.py 部署、交互和签署交易。让我们通过查看我使用 web3.py 创建的实时 DApp 并在此处使用 Flask 作为前端服务器来将所有部分组合在一起。它将帮助您更深入地了解使用 Python 进行 DApp 开发。8 x3 T- P! a. Z5 P: {. m
# Q v7 W- E5 x) V3 r2 {
3 [! d/ o; G0 w* Q
参考 @温室小书生室d 《python利用web3.py开发以太坊应用dapp的实战教程》



