模板文件是放在目录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