那麼它真的很簡單,它是所有關於你如何在HTML模板呈現形式,讓您的視圖來獲取表單數據,並通過上下文回模板。
我趕緊嘲笑像你想要什麼樣(沒有什麼特別的,只是回到基本,並告訴你如何將這些一起工作),它的代碼只有幾行的2個文件main.py(核心文件,就像一個視圖邏輯)和一個模板calculation.html:
main.py
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def calculation():
result = 0
error = ''
# you may want to customize your GET... in this case not applicable
if request.method=='POST':
# get the form data
first = request.form['first']
second = request.form['second']
if first and second:
try:
# do your validation or logic here...
if int(first)>10 or int(first)<1:
raise ValueError
result = int(first) + int(second)
except ValueError:
# you may pass custom error message as you like
error = 'Please input integer from 1-10 only.'
# you render the template and pass the context result & error
return render_template('calculation.html', result=result, error=error)
if __name__ == "__main__":
app.run()
模板/ calculation.html
<h1>Calculation</h1>
<form method="POST">
<input type="text" name="first" value="">
<select name="second">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" value="Submit">
{% if result %}
<p>
<label name='result'>Answer is: {{ result }}</label>
</p>
{% endif %}
{% if error %}
<p>
<label name="error">{{ error }}</label>
</p>
{% endif %}
</form>
希望這些都是自我解釋,你可以去了解如何與瓶形式基本等
讀Flask Doc工作,並試圖跟進,他們是真的很簡單一旦你指定了基礎,你可能會開始尋找中級和前進的話題。
僅供參考,有一個WTForms稱爲Flask-WTF的延伸,它與形式打交道時非常方便,雖然沒有什麼可以阻止你只是在做純HTML格式如上面的代碼中的一切。
希望這有助於我希望你喜歡簡單和靈活Flask帶給你。
太棒了!正是我需要的!很高興這很簡單,我希望它是! – zanzu 2014-12-29 17:52:35