使用原生python进行渲染显得非常僵硬,使用render_template等方式就会非常灵活的显示出来。
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): # use http methods if request.method == 'POST': # request.form.get:获取单个参数的值 uname = request.form.get('uname') # 这个并不是最好的显示方式,如果key写错了,那么uname直接为None。你可以设置一个默认参数,像这样:uname = request.form.get('uname', '') upwd = request.form.get('upwd') return render_template('index.html', params={'name':uname, 'pwd':upwd}) # 渲染模板 return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>index</title>
</head>
<body>
<!-- 接收传递过来的参数,值得注意的是其结构(if...else...endif...)和分离方式({%%}用来做判断,{{}}用来显示单个值) -->
{% if params %}
<p><b>{{ params["name"] }}</b><span>{{ params["pwd"] }}</span></p>
{% else %}
<form action="" method="post">
username:<input type="text" name="uname"><br>
password:<input type="password" name="upwd"><br>
<input type="submit" value="sub">
</form>
{% endif %}
</body>
</html>