Python Flask框架實現簡單加法工具過程解析
阿新 • • 發佈:2020-06-04
主程式mainaddfunc.py
from flask import Flask,render_template,request,url_for from add import * app = Flask(__name__) @app.route('/',methods=['GET']) def home(): return render_template('index.html') @app.route('/',methods=['POST']) def add(): a = request.form['adder1'] b = request.form['adder2'] try: a = float(a) b = float(b) result = sum_function(a,b) return render_template('index.html',result=result,var1=a,var2=b) except: return render_template('index.html',message='inputs false!!!',var2=b) if __name__ == '__main__': app.run(port=8080)
大家可以對比原作者的程式碼可以發現,我這裡的result呼叫了一個python的子函式sum_function,或許有的同學可能會說,這麼簡單的加法呼叫神馬子程式,不嫌麻煩,話是如此,但是一個簡單的呼叫可以開啟子函式的新大門,遇到麻煩的函式的時候,只需要想想這個模板可行,自然而然就用到函式呼叫了。修改的第二點加入了try語句,判斷輸入的加數是否是數字,當不是浮點數的時候,報錯。修改的第三點可以看見加入了var1和var2兩個變數,也就是兩個加數作為了變數傳遞給了html。這麼做的好處是什麼,來,先看下一段程式碼index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>加法</title> </head> <body> <div align="center" style="margin-top: 40px;"> <form name="form1" method="POST"> <input type="text" placeholder="adder" name="adder1" value="{{ var1 }}">+ <input type="text" placeholder="adder-2" name="adder2" value="{{ var2 }}">= <input type="text" readonly="readonly" placeholder="result" name="result" value="{{ result }}"> <input type="submit" value="計算" οnclick=""> </form> </div> {% if message %} <p style="color:red">{{ message }}</p> {% endif %} </body>
對比原作者的程式碼,我加入了value="{{ var1 }}和value="{{ var2 }},這麼做的好處就是輸入了兩個加數之後,點選計算按鈕之後,輸入的加數仍然在框框裡,不會隨著重新整理顯示不見,原作者在最後也發現了這個問題,我做了改進,最後是執行的結果
正確輸入和錯誤輸入的情況下:
就這樣了。初學的同學,小提示一下,在谷歌瀏覽器輸入http://localhost:8080/就可以看到執行結果了,畢竟flask是用來做web的。最後貼上我的py子函式add.py
def sum_function(a,b): c = a + b return c
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。