# Flask實作_基礎_09_redirect after some action ###### tags: `python` `flask` `redirect` 在作業流程中,可能使用者執行了某一個動作之後我們需要將使用者引導到另一個頁面,這種重新導向的動作在flask中可以利用內建函數`redirect`來達成。 ## 作業說明 延續[Flask實作_基礎_08_form action url_for](https://hackmd.io/s/Bk2QpUAlG)的案例,普遍來說,在使用者按下登入頁面之後會驗證帳號密碼,驗證失敗就顯示登入失敗訊息,驗證成功則引導使用者到另一個頁面去。 範例上我們只是要瞭解`redirect`的作用,所以不需要很複雜的調整,我們只需要小調一下Python文件跟新增一個html文件 先調整Python文件如下: ```python= from flask import Flask, request, render_template, redirect, url_for app = Flask(__name__) @app.route('/loginurl', methods=['GET', 'POST']) def login(): if request.method == 'POST': return redirect(url_for('hello', username=request.form.get('username'))) return render_template('login.html') @app.route('/hello/<username>') def hello(username): return render_template('hello.html', username=username) if __name__ == '__main__': app.debug = True app.run() ``` 第7行:判斷`request.method`是否來自`POST` 第8行:利用`redirect(url_for('function'))`重新導向,將使用者導到`@app.route('/hello/<username>')`,並且傳遞參數`username`<sub><a href='#note_1'>(註1)</a></sub>。 接著加入新的HTML文件如下: * file name: hello.html ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> hello, {{ username }}, Welcome my homepage! </body> </html> ``` 第8行:設置參數`username` * file name: login.html ```htmlmixed= <!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> ``` 執行專案,連結相對應的路由網址,結果如下:  在按下`Submit`之後,透過`redirect`將使用者重新導向到`url_for('hello')`,並順便傳遞參數`username`給`hello.html`模板中的`{{ username }}`。 ## 註解說明 <span id='note_1'>註1</span>:這邊用了另一種方式來取得`username`,`request.form.get('Your Parameter')` ## 總結 應用`redirect`配合`url_for`的作法在flask中是非常常見的作法,這次我們除了將兩者結合使用之外還搭配參數`username`的傳遞,幾個案例操作下來,應該對flask有更深的瞭解,接下來我們要認識flask中的`flash`,這是一個訊息發送的功能,也是實用性很高的一個function。 **上一話:**[Flask實作_基礎_08_form action url_for](https://hackmd.io/s/Bk2QpUAlG) **下一話:**[Flask實作_基礎_10_flash message](https://hackmd.io/s/BkkbvYIff)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up