Flask 模板,静态文件,POST传值

本文详细介绍了一个基于Flask框架的Web应用程序实例,包括模板文件、静态文件的组织方式,以及如何通过Jinja2语法处理表单数据并显示结果。具体涵盖了Flask的路由设置、请求处理和模板渲染等关键环节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板文件是放在目录templates下,静态文件放在目录static下;
模板使用Jinja2语法;

首页模板./templates/index.html

<html>
    <head>
        <title>{{title}}</title>
        <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
    </head>

    <body>
        <form action = "http://localhost:8080/result" method = "POST">
            <p>Name <input type = "text" name = "Name" /></p>
            <p>Physics <input type = "text" name = "Physics" /></p>
            <p><input type = "submit" value = "submit" /></p>
        </form>
    </body>
</html>

处理结果页模板./templates/result.html

<!doctype html>
<html>
    <body>
        <table border = 1>
            {% for key, value in info.items() %}
                <tr>
                    <th> {{ key }} </th>
                    <td> {{ value }} </td>
                </tr>
            {% endfor %}
        </table>
    </body>
</html>

静态文件./static/hello.js

function sayHello() {
    alert("Hello World")
}

控制器文件IndexController.py

from flask import Flask, render_template, request;

app = Flask(__name__);
app.strict_slashes = False;

# 首页
@app.route('/')
@app.route('/index')
def index():
    # 定义模板变量title
    return render_template('index.html',title = 'Home');

# 处理结果页
@app.route('/result',methods = ['POST', 'GET'])
def result():
    res = {};
    if request.method == 'POST':
        res = request.form;
    if request.method == 'GET':
        res['Name'] = request.args.get('Name');
        res['Physics'] = request.args.get('Physics');
    # 将结果赋值给模板变量info
    return render_template("result.html", info = res);


if __name__ == '__main__':
    app.run('0.0.0.0', 8080, debug = True);

运行

$ python IndexController.py

访问

//# POST
http://127.0.0.1:8080/

//# GET
http://127.0.0.1:8080/result?Name=test&Physics=80

参考
https://www.tutorialspoint.com/flask/flask_sending_form_data_to_template.htm

相关文章
简单应用- Hello world
Flask 路由和URL传参数
Flask 转跳和构造URL

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值