Django網站製作根目錄,巧用404,可訪問根目錄任意網頁

在製作網頁過程中,網站需要格式各樣的驗證。比如百度站長、搜狗聯盟的校驗網站。不止如此,有時寫一個靜態頁面,也沒有必要再去搞一個路由出來。這個時候,想到Django的404頁面的定義,所有的不存在的頁面會被定向到404頁面,那麼就在這塊加點邏輯。首先,再setting配置文件得到自己的根目錄,我定義根目錄在網站之下的root目錄

1 TEMPLATES = [
2 {
3 'BACKEND': 'django.template.backends.django.DjangoTemplates',
4 'DIRS': [os.path.join(BASE_DIR, 'bianbingdang/root'),]
5 ]

在urls.py文件當中寫入如下邏輯

1 from django.conf import urls
2 from .views import page_not_found
3 urls.handler404 = page_not_found

在views.py定義邏輯如下,也就是說,當發現root目錄下存在請求的文件時,就向瀏覽器返回該頁面:

Django網站製作根目錄,巧用404,可訪問根目錄任意網頁

 1 import os
2 from django.shortcuts import render_to_response
3 from .settings import TEMPLATES
4 def page_not_found(request, **kwargs):
5 root_templates = os.listdir(TEMPLATES[0]['DIRS'][-1])
6 print(request.path[1:] in root_templates)
7 if request.path[1:] in root_templates:
8 print(request.path)
9 return render_to_response(request.path[1:])
10 return render_to_response('error/404.html')


分享到:


相關文章: