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