1. 程式人生 > >python測試開發django-3.url配置

python測試開發django-3.url配置

path ise reg html模板 處理 url路徑 tro 內容 參數化

前言

我們在瀏覽器訪問一個網頁是通過url地址去訪問的,django管理url配置是在urls.py文件。當一個頁面數據很多時候,通過會有翻頁的情況,那麽頁數是不固定的,如:page=1.
也就是url路徑裏面帶參數時候如何去處理呢?

urls.py配置規則

由於django版本比較多,在查資料時候,也會看到不同的版本用不同寫法,對於初學者來說是比較迷惑的,
總結了下,主要有三個:path、re_path、url,接下來具體分析下這三個有什麽區別。

  • path 只能絕對匹配路徑地址,不支持正則匹配
  • re_path 支持正則匹配,django 1.x版本常用
  • url 支持正則匹配,實際上就是return re_path, django2.x版本推薦
# helloworld/urls.py
from django.conf.urls import url
from django.urls import re_path, path
from hello import views

urlpatterns = [
    path("index/", views.index),
    re_path('^$', views.index),
    url('^demo/$', views.demo),
]

在瀏覽器上訪問http://127.0.0.1:8000/index/, http://127.0.0.1:8000/, http://127.0.0.1:8000/demo/ 發現都能正確訪問到對應內容。

打開path()和re_path()源碼,就能看到path()的匹配規則是RoutePattern, re_pat()h匹配規則是RegexPattern

path = partial(_path, Pattern=RoutePattern)
re_path = partial(_path, Pattern=RegexPattern)

再打開url()對應的源碼,實際上就是return re_path(),後續統一用url()就可以了。

def url(regex, view, kwargs=None, name=None):
    return re_path(regex, view, kwargs, name)

匹配路徑統一在後面加個/,前面不用加/,如:index/、demo/、demo/page/

url加變量

當訪問的頁面有分頁的情況,對應的頁數就不能寫死,如訪問:http://127.0.0.1:8000/demo/page=1 ,那就不能這樣寫死了

url(‘^demo/page=1$‘, views.demo)

如果想匹配任意的頁數,前面的部分demo/page=不變,匹配任意數字,可以用正則\d+匹配

url(‘^demo/page=\d+$‘, views.demo)

這樣在瀏覽器上輸入任意page頁數都能訪問一個固定地址,依然不是我們想要的結果,我們希望不同的頁數,訪問不同的地址,於是可以寫個帶參數的視圖函數

hello/views.py文件寫個帶參數的視圖函數,當輸入的page=後面不是數字就拋個異常404

from django.shortcuts import render
from django.http import HttpResponse, Http404

# Create your views here.

def index(request):
    return HttpResponse("Hello world !  django ~~")

def demo(request):
    return render(request, 'demo.html')

def page(request, num):
    try:
        num = int(num)
        return render(request, 'demo.html')
    except:
        raise Http404

urls.py配置

from django.conf.urls import url
from django.urls import re_path, path
from hello import views
urlpatterns = [
    path("index/", views.index),
    re_path('^$', views.index),
    url('^demo/$', views.demo),
    url('^demo/page=(\d+$)', views.page),
]

接下來可以瀏覽器輸入:http://127.0.0.1:8000/demo/page=222 ,能返回demo.html頁面。
視圖函數裏面返回的是一個靜態的demo.html模板頁面,後面會講模板參數化配置

404報錯頁面

如果輸入的page不是數字,如:http://127.0.0.1:8000/demo/page=aa , 會出現報錯頁面:Page not found (404)

技術分享圖片

看到這種報錯頁面,因為Django設置文件setting.py裏面有個參數 DEBUG = True,將其更改為False,Django將顯示標準的404頁面。

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

由於處於開發階段,DEBUG 默認為True,當開發完成正式發布產品上線時,需要將DEBUG = False

改成False之後,需要重新啟動服務,同時需要加個ALLOWED_HOSTS 地址,如:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["127.0.0.1"]

執行:>python manage.py runserver 重新啟動後,出現404就是下面這種標準的了

技術分享圖片

django更多關於urls學習可以參考【https://docs.djangoproject.com/zh-hans/2.0/topics/http/urls/】
python學習交流QQ群:588402570

python測試開發django-3.url配置