涉及知识点:
- render_template()
- redirect():注意def的函数不要使用这个Python关键字
- url_for():可以传参数给动态路由
- 动态路由
# Sample.py from flask import Flask, render_template, url_for, request, redirect app = Flask(__name__) @app.route('/')
def hello_world():
return 'hello,world' @app.route('/user/<username>', methods=['POST', 'GET'])
def user(username):
return 'Hello,%s' % username @app.route('/user/login')
def login():
return render_template('login.html') @app.route('/user/redirect', methods=['POST'])
def redirect_to_new_url():
username = request.form['username']
return redirect(url_for('user',username=username)) if __name__ == '__main__':
app.run(debug=True)
/ template/
#login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>请登陆会员账号</title>
</head>
<body>
<h2>请登陆您的会员账号</h2>
<form action='{{ url_for('.redirect_to_new_url') }}' method="POST">
<table>
<tr>
<td>会员名:</td>
<td><input type="text" name='username' placeholder="Username" value="BIKMIN"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name='password' placeholder="Password"></td>
</tr>
<tr>
<td><input type="submit" value="登陆"></td>
</tr>
</table>
</form>
</body>
</html>
测试运行
点击登陆后,会重定向至由动态路由
--------------------------- 完 ------------------------------------------