在EOSIO平臺上開發區塊鏈dapp(三、webapp)
以下是webapp的快速預覽:
源代碼說明
首先,請參閱下面的概述圖:
前端
前端由HTML,CSS和Javascript組成。我使用Semantic-UI
作為CSS框架以獲得漂亮的外觀。JQuery在Javascript中被大量使用以便於開發。
此webapp只有一個頁面(主頁HTML)。主頁分為四個部分。 以下是部分的屏幕截圖:
以下是主頁index.html
的代碼片段:
... <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
的完整源代碼在這裏
app.js
涵蓋了前端邏輯。以下是亮點:
... // 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()
來執行對後端的多次異步調用。以下部分將提到後端代碼。
後端
後端用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入門開發實戰教程
在EOSIO平臺上開發區塊鏈dapp(三、webapp)