|
在一般的網頁操作中,使用者執行某一個動作之後,我們需要將使用者引導到另一個頁面,這個動作可以透過redirect來達成。
使用者按下Submit之後通常會經過驗證,驗證成功會引導使用者到下一個頁面。所以我們要做的是登入後,透過redirect做到畫面跳轉。
新增一個新的html文件
- from flask import Flask, request, redirect, url_for, render_template
- # 固定格式
- app = Flask(__name__)
- @app.route('/loginurl', methods=['GET', 'POST'])
- def login():
- if request.method == 'POST':
- # 使用redirect(url_for('function')) 重新導向到要跳轉的function及url
- retrun redirect(url_for('hello', username=request.form.get('username')))
-
- return render_template('login.html')
- # 接收login()內的redirect(url_for('function'))傳遞的參數
- @app.route('/hello/<username>')
- def hello(username):
- return render_template('hello.html', username=username)
- if __name__ == "__main__":
- app.run(debug=True)
複製代碼
第8行:判斷request.method使否為POST
第10行:使用redirect(url_for('function'))重新導向到@app.route('/hello/<username>'),並傳遞參數username
新增 hello.html文件
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF_8">
- <title>
- Hello
- </title>
- </head>
- <body>
- hello, {{username}}, Welcome my homepage
- </body>
- </html>
複製代碼
第10行:設置參數username,會接收來自@app.route('/hello/<username>')內的參數
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF_8">
- <title>
- Hello Page
- </title>
- </head>
- <body>
- <form method="post" action={{url_for('login')}}>
- <p>
- <input type="text" name="username">
- </p>
- <p>
- <button type="submit">
- Submit
- </button>
- </p>
- </form>
- </body>
- </html>
複製代碼
登入畫面如下圖所示:
成功透過redirect做到畫面跳轉,如下圖所示:
按下Submit之後,透過redirect將使用者重新導向到url_for('hello'),並順利傳遞參數username給hello.html文件中的{{username}}
|
|