Flask入門之開發簡單登陸界面


 

涉及知識點:

  • 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>

 

 測試運行

點擊登陸后,會重定向至由動態路由

 

---------------------------     完    ------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM