好吧,这真的很简单,这都是关于如何在html模板中呈现表单,获取视图以获取表单数据以及将上下文传递回模板的全部内容。
我很快就嘲笑了一个您想要的示例(没什么花哨的内容,回到基础并向您展示它们如何协同工作),在2个文件 main.py
(核心文件,如视图逻辑)中只有几行代码)和模板 Calculation.html :
main.py
from flask import Flaskfrom flask import render_templatefrom flask import requestapp = 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()
templates / 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 和表单等基础知识。
阅读Flask
Doc,然后尝试继续学习,它们确实非常简单,一旦您掌握了基础知识,就可以开始寻找中级和高级主题。
仅供参考, WTForms 的扩展名为Flask-WTF,在处理表单时非常方便,尽管没有什么可以阻止您像上面的代码那样以纯HTML形式进行所有 *** 作。
希望这会有所帮助,并希望您喜欢 Flask 带来的简单性和灵活性。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)