找回密碼
 註冊
搜索
查看: 99|回復: 0

[教學] Flask redirect to other url after action

[複製鏈接]
發表於 3 天前 | 顯示全部樓層 |閱讀模式
Push to Facebook
在一般的網頁操作中,使用者執行某一個動作之後,我們需要將使用者引導到另一個頁面,這個動作可以透過redirect來達成。

使用者按下Submit之後通常會經過驗證,驗證成功會引導使用者到下一個頁面。所以我們要做的是登入後,透過redirect做到畫面跳轉。

新增一個新的html文件


  1. from flask import Flask, request, redirect, url_for, render_template

  2. # 固定格式
  3. app = Flask(__name__)

  4. @app.route('/loginurl', methods=['GET', 'POST'])
  5. def login():
  6.     if request.method == 'POST':
  7.         # 使用redirect(url_for('function')) 重新導向到要跳轉的function及url
  8.         retrun redirect(url_for('hello', username=request.form.get('username')))
  9.         
  10.     return render_template('login.html')

  11. # 接收login()內的redirect(url_for('function'))傳遞的參數
  12. @app.route('/hello/<username>')
  13. def hello(username):
  14.     return render_template('hello.html', username=username)

  15. if __name__ == "__main__":
  16.     app.run(debug=True)
複製代碼

第8行:判斷request.method使否為POST
第10行:使用redirect(url_for('function'))重新導向到@app.route('/hello/<username>'),並傳遞參數username

新增 hello.html文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF_8">
  5.     <title>
  6.         Hello
  7.     </title>
  8. </head>
  9. <body>
  10.     hello, {{username}}, Welcome my homepage
  11. </body>

  12. </html>
複製代碼

第10行:設置參數username,會接收來自@app.route('/hello/<username>')內的參數

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF_8">
  5.     <title>
  6.         Hello Page
  7.     </title>
  8. </head>
  9. <body>
  10.     <form method="post" action={{url_for('login')}}>
  11.         <p>
  12.             <input type="text" name="username">
  13.         </p>
  14.         <p>
  15.             <button type="submit">
  16.                 Submit
  17.             </button>
  18.         </p>   
  19.     </form>
  20. </body>
  21. </html>
複製代碼

登入畫面如下圖所示:

成功透過redirect做到畫面跳轉,如下圖所示:

按下Submit之後,透過redirect將使用者重新導向到url_for('hello'),並順利傳遞參數username給hello.html文件中的{{username}}
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-6-30 17:55 , Processed in 0.023829 second(s), 20 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表