您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

用于Python功能的Web UI

用于Python功能的Web UI

好吧,这真的很简单,这都是关于如何在html模板中呈现表单,获取视图以获取表单数据以及将上下文传递回模板的全部内容

我很快就嘲笑了一个您想要的示例(没什么花哨的内容,回到基础并向您展示它们如何协同工作),在2个文件 (核心文件,如视图逻辑)中只有几行代码)和模板 :

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()

<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,然后尝试继续学习,它们确实非常简单,一旦您掌握了基础知识,就可以开始寻找中级和高级主题

仅供参考, 的扩展名为Flask-WTF,在处理表单时非常方便,尽管没有什么可以阻止您像上面的代码那样以纯HTML形式进行所有操作。

希望这会有所帮助,并希望您喜欢 带来的简单性和灵活性。

python 2022/1/1 18:47:07 有350人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶