1、django搜索路徑
使用 import 語句時,Python 所查找的系統目錄清單。
查看方式:
import sys
print sys.path
通常無需關心 Python 搜索路徑的設置,Python 和 Django 會在后台自動幫你處理好。
2、url匹配模式
基本結構:
'^需要匹配的url字符串$'
PS:實際上最終完整的url串是http://根路徑:端口號/需要匹配的url字符串
系統自動添加的部分'http://根路徑:端口號/'
eg:url匹配模式:'^latest_books/$'
最終完整的url字符串:'http://127.0.0.1:8000/latest_books/'
1)^:匹配“子串頭”。
eg:
'^latest_books/' 'http://127.0.0.1:8000/latest_books/', 'http://127.0.0.1:8000/latest_books/test1/', 'http://127.0.0.1:8000/latest_books/test2/', 'http://127.0.0.1:8000/latest_books/test1/aaa/'
都會被匹配上。
2)$:匹配“子串結尾”。
eg:
'latest_books/$' 'http://127.0.0.1:8000/latest_books/', 'http://127.0.0.1:8000/updir_1/latest_books/', 'http://127.0.0.1:8000/updir_2/latest_books/'
都會被匹配上。
3)子串末尾是否包含'/'
默認情況下必須添加(django開發者的基本習慣),如果不添加將會出現如下情況:
from django.conf.urls import patterns, url, include urlpatterns = patterns('', (r'^latest_books$', 'django_web_app.views.latest_books'), )
如果子串末尾不想包含'/',可在setting.py中添加設置:APPEND_SLASH=False
但是必須安裝了CommonMiddleware才會起作用。
4)手動配置網站“根目錄”
在不手動配置網站“根目錄”對應“視圖函數”的情況下,會出現如下情況:
手動配置“根目錄”對應“視圖函數”:
a)urls.py
from django.conf.urls import patterns, url, include urlpatterns = patterns('', (r'^$','django_web_app.views.home_page'), (r'^latest_books/$', 'django_web_app.views.latest_books'), )
b)views.py
def home_page(request): return render_to_response('home_page.html')
c)home_page.html
<!DOCTYPE html> <html> <head> <title>my home page</title> </head> <body> <h1>This is home page, welcome !</h1> </body> </html>
運行結果:
附:正則表達式基礎
3、服務端響應url請求的執行順序
1)項目結構
django_web
__init__.py
settings.py
urls.py
wsgi.py
django_web_app
__init__.py
admin.py
models.py
tests.py
views.py
templates
home_page.html
latest_books.html
manage.py
2)執行順序
a)啟動服務端——python manage.py runserver
獲取setting.py文件中的配置,主要包括:
url映射關系文件路徑:
ROOT_URLCONF = 'django_web.urls'
頁面文件模板路徑:
TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), )
數據庫配置:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER': 'root', 'PASSWORD': 'feng', 'HOST': '127.0.0.1', 'PORT': '3306', } }
b)響應順序
第一步:瀏覽器提交請求
http://127.0.0.1:8000/latest_books/
第二步:服務端根據請求的url在urls.py中進行匹配,並找到對應的“視圖函數”
第三步:調用對應的“視圖函數”
返回一個HttpResponse對象
第四步:django轉換HttpResponse對象為一個適合的HTTP response,並返回給頁面進行顯示