這是一步步的用EOSIO開發區塊鏈DApp的第三部分,上一部分中,我爲EOSIO平臺開發了一個模擬選舉的智能合約。這部分我將開發一個webapp,容許訪問者投票給候選人。html
如下是webapp的快速預覽:前端
首先,請參閱下面的概述圖:node
前端由HTML,CSS和Javascript組成。我使用Semantic-UI
做爲CSS框架以得到漂亮的外觀。JQuery在Javascript中被大量使用以便於開發。git
此webapp只有一個頁面(主頁HTML)。主頁分爲四個部分。 如下是部分的屏幕截圖:github
如下是主頁index.html
的代碼片斷:web
...
<body>
<div class="ui container">
<div class="ui grid">
...
<div id="hints_portion" class="sixteen wide column">
...
</div>
<div id="input_portion" class="sixteen wide column">
...
</div>
<div id="voting_portion" class="sixteen wide column">
...
</div>
<div id="voted_portion" class="sixteen wide column">
...
</div>
...
</div>
</div>
...
複製代碼
index.html
的完整源代碼在這裏ajax
app.js
涵蓋了前端邏輯。如下是亮點:shell
...
// Main Application Object
function App() {
...
}
...
// Ajax calls
App.prototype.getInfo = function() {
return $.ajax({
type: 'GET',
dataType: 'json',
url: '/api/getinfo'
});
}
App.prototype.unlockWallet = function() {
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/api/unlock_wallet'
});
}
...
// Event handlers
App.prototype.onBtnInputNameClicked = function(evt) {
...
}
...
// Program startup
App.prototype.start = function() {
self.getInfo().then(function() {
return self.unlockWallet();
}).done(function() {
...
}
}
...
複製代碼
app.js
的完整源代碼在這裏編程
如你所見,我使用jQuery ajax()
和then()
來執行對後端的屢次異步調用。如下部分將提到後端代碼。json
後端用Python和Flask框架編程。Flask不只使咱們可以很是輕鬆地建立功能強大的Web應用程序,並且能夠快速開發RESTful API服務。如下是server.py
代碼的代碼亮點:
import subprocess
from flask import Flask
from flask import render_template
...
def cleos(args):
if isinstance(args, list):
command = ['cleos', '--wallet-url=http://localhost:8899']
command.extend(args)
command = ' '.join(command)
else:
command = 'cleos ' + args
results = subprocess.run(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, check=False)
return results
...
app = Flask(__name__)
...
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html')
...
# RESTful API functions
@app.route('/api/getinfo', methods=['GET'])
def get_info():
result = cleos(['get', 'info'])
rstmsg = result.stderr.decode('ascii')
if not rstmsg.startswith('Fail'):
return result.stdout
else:
return 'nodeos connection failed', 500
...
複製代碼
server.py
的完整源代碼在這裏
如上所述,在cleos()
函數內部,它生成新進程以啓動cleos命令,就像在命令行中同樣。你可能想知道爲何不使用EOSJS。事實上,在EOSJS中建立EOSIO賬戶存在問題。實際上,我嘗試使用NodeJS代碼在EOSJS中建立一個賬戶,但都失敗了。因此我放棄了並切換到Python Flask。雖然子進程很慢而且具備可擴展性問題。但我認爲它適合於演示目的。
這種方法使我能夠輕鬆調用EOSIO智能合約。下面的server.py
中的代碼片斷說明了如何調用智能合約在上一部分最後小結開發的投票操做:
...
@app.route('/api/vote_candidate', methods=['POST'])
def vote_candidate():
account = request.form.get('account')
candidate = request.form.get('candidate')
param = '\'["' + account + '", ' + candidate + ']\''
# Invoke the Smart Contract "vote" action
result = cleos(['push', 'action', 'election', 'vote', param, '-p', account])
print(result.stderr)
if result.returncode == 0:
return jsonify({'result': result.stderr.decode('ascii')})
else:
return result.stderr, 500
...
複製代碼
所以前端代碼app.js
調用:
...
App.prototype.voteCandidate = function(account, candidate) {
return $.ajax({
type: 'POST',
data: {
account: account,
candidate: candidate
},
dataType: 'json',
url: '/api/vote_candidate'
});
}
...
this.voteCandidate(this._account, val).done(function(resp) {
console.info('Vote AJAX call result');
console.log(resp);
...
複製代碼
我已經設置了一個演示服務器,讓你體驗EOSIO區塊鏈。瀏覽http://demo.simonho.net:5000本身嘗試一下。但我沒法保證服務器隨時可用且持久。它只是我家用電腦的虛擬機。
這就是個人EOSIO區塊鏈實驗系列的所有內容。先前部分的超連接:第1部分和第2部分。
但願你喜歡!
項目完整源代碼託管在這裏github repo
安利一個EOS智能合約與DApp開發入門交互式的在線編程實戰:
本課程幫助你快速入門EOS區塊鏈去中心化應用的開發,內容涵蓋EOS工具鏈、帳戶與錢包、發行代幣、智能合約開發與部署、使用代碼與智能合約交互等核心知識點,最後綜合運用各知識點完成一個便籤DApp的開發。
這裏是原文