
- Python - 網路程式設計
- Python - 網路入門
- Python - 網路環境
- Python - 網際網路協議
- Python - IP 地址
- Python - DNS 查詢
- Python - 路由
- Python - HTTP 請求
- Python - HTTP 響應
- Python - HTTP 頭部
- Python - 自定義 HTTP 請求
- Python - 請求狀態碼
- Python - HTTP 認證
- Python - HTTP 資料下載
- Python - 連線重用
- Python - 網路介面
- Python - 套接字程式設計
- Python - HTTP 客戶端
- Python - HTTP 伺服器
- Python - 構建 URL
- Python - Web 表單提交
- Python - 資料庫和 SQL
- Python - Telnet
- Python - 電子郵件
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web 伺服器
- Python - 上傳資料
- Python - 代理伺服器
- Python - 目錄列表
- Python - 遠端過程呼叫
- Python - RPC JSON 伺服器
- Python - 谷歌地圖
- Python - RSS Feed
Python - 路由
路由是將 URL 直接對映到建立網頁的程式碼的機制。它有助於更好地管理網頁結構,並顯著提高網站效能,並進一步簡化增強或修改。在 python 中,路由在大多數 web 框架中都有實現。在本章中,我們將從flask web 框架中檢視示例。
Flask 中的路由
Flask 中的route()裝飾器用於將 URL 繫結到函式。因此,當瀏覽器中輸入 URL 時,將執行該函式以給出結果。這裡,URL '/hello'規則繫結到hello_world()函式。因此,如果使用者訪問https://:5000/ URL,則hello_world()函式的輸出將在瀏覽器中呈現。
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello Tutorialspoint' if __name__ == '__main__': app.run()
當我們執行上述程式時,我們將得到以下輸出:
* Serving Flask app "flask_route" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [06/Aug/2018 08:48:45] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [06/Aug/2018 08:48:46] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [06/Aug/2018 08:48:46] "GET /favicon.ico HTTP/1.1" 404 -
我們開啟瀏覽器並指向 URL https://:5000/以檢視正在執行的函式的結果。

使用 URL 變數
我們可以使用 route 傳遞 URL 變數來動態構建 URL。為此,我們使用 url_for() 函式,該函式接受函式名稱作為第一個引數,其餘引數作為 URL 規則的可變部分。
在下面的示例中,我們將函式名稱作為引數傳遞給 url_for 函式,並在執行這些行時打印出結果。
from flask import Flask, url_for app = Flask(__name__) @app.route('/') def index(): pass @app.route('/login') def login(): pass @app.route('/user/') def profile(username): pass with app.test_request_context(): print url_for('index') print url_for('index', _external=True) print url_for('login') print url_for('login', next='/') print url_for('profile', username='Tutorials Point')
當我們執行上述程式時,我們將得到以下輸出:
/ https:/// /login /login?next=%2F /user/Tutorials%20Point
重定向
我們可以使用 redirect 函式透過路由將使用者重定向到另一個 URL。我們將新 URL 作為函式的返回值,該函式應重定向使用者。當我們在修改現有網頁時暫時將使用者轉移到不同的頁面時,這很有用。
from flask import Flask, abort, redirect, url_for app = Flask(__name__) @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login') def login(): abort(401) # this_is_never_executed()
執行上述程式碼時,基本 URL 會轉到登入頁面,該頁面使用 abort 函式,以便登入頁面的程式碼永遠不會執行。
廣告