【人工智慧雲端系統實務】 08. Django URLs 解析與應用
在 Django 中,urls.py 是「網址路由系統」的核心,負責將網站中的每個網址(URL)對應到一個特定的 View。它就像一張地圖,決定使用者請求的網址該交由哪個處理函式來處理。
1. Django URL 處理流程簡介
當使用者訪問一個網址(如 /articles/
)時,Django 會從 urls.py
開始比對網址路徑,找到對應的 View 並執行。
流程如下:
1
| 瀏覽器 → URL → Django URLconf → 對應 View → 回應內容(HTML/JSON)
|
2. 專案與應用程式中的 urls.py
2.1 專案層的 urls.py
這是專案啟動時的主要 URL 配置,一般在 project/urls.py
:
1 2 3 4 5 6 7 8
| from django.contrib import admin from django.urls import path, include
urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ]
|
2.2 應用層的 urls.py
每個 app 都可以擁有自己的 URL 配置檔:
1 2 3 4 5 6 7 8
| from django.urls import path from . import views
urlpatterns = [ path('', views.home_view, name='home'), path('about/', views.about_view, name='about'), ]
|
3. 基本語法與結構
1 2 3 4 5 6
| from django.urls import path from . import views
urlpatterns = [ path('路徑字串/', views.對應函式, name='命名路由'), ]
|
範例:
1
| path('hello/', views.hello_view, name='hello')
|
當使用者訪問 /hello/
,將會由 hello_view()
處理。
4. 傳遞 URL 參數給 View
Django 支援動態 URL 參數,可以將變數(如 ID、slug)傳入 View。
4.1 整數參數
1
| path('article/<int:id>/', views.article_detail, name='article_detail')
|
1 2 3
| def article_detail(request, id): return HttpResponse(f"你正在查看第 {id} 篇文章")
|
4.2 字串參數(slug)
5. 使用 include()
分割路由
當網站變大時,將不同 app 的 URL 獨立管理是良好的做法:
1 2 3 4 5
| urlpatterns = [ path('blog/', include('blog.urls')), path('shop/', include('shop.urls')), ]
|
這樣每個應用都可獨立擁有自己的路由設定。
6. 命名路由與 reverse()
6.1 定義命名路由
1
| path('login/', views.login_view, name='login')
|
6.2 在模板中使用 {% url %}
1
| <a href="{% url 'login' %}">登入</a>
|
6.3 在 Python 中使用 reverse()
1 2 3
| from django.urls import reverse
url = reverse('login')
|
6.4 Namespace 路由命名空間
1 2
| path('blog/', include(('blog.urls', 'blog'), namespace='blog'))
|
1
| <a href="{% url 'blog:post_list' %}">所有文章</a>
|
7. 支援 re_path()
使用正規表達式
如果需要更彈性/複雜的 URL 配對,可用 re_path
搭配 regex:
1 2 3
| from django.urls import re_path
re_path(r'^page/(?P<page_num>\d{1,3})/$', views.page_view)
|
8. URL 設計最佳實踐
做法 |
原因 |
使用 include() 分割大型網站的路由 |
更易維護與擴充 |
為每條路由設定 name |
方便模板與重構時不需改硬編碼網址 |
盡量使用語意化 URL(如 /post/123/ ) |
提高 SEO 與可讀性 |
避免在 urls.py 中寫太多邏輯 |
URL 應單純對應 View,不進行資料處理 |
搭配 namespace 區分不同 App 的路由 |
避免名稱衝突,提升模組化程度(下節補充可說明) |
留言