1 建立視圖
進入到第二個mysite目錄。建立立views.py檔案。
代碼如下:
from django.http import HttpResponse
def hello(request):
return HttpResponse('hello world')
可以知道,視圖檔案,從django中引入子產品http,并導入HttpResponse函數。視圖中一個hello函數。其中的reutrn HttpResponse可以了解為c#中的response.Write。
2 建立路由
通過浏覽器的位址,從路由中去比對視圖。
在urls.py檔案中配置路由。
from django.conf.urls import patterns, include, url
from mysite.views import *
urlpatterns = patterns('',
(r'^hello/',hello),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
<a href="mailto:%E4%B8%8A%E8%BE%B9%E7%AC%AC%E4%BA%8C%E8%A1%8C%E7%BA%A2%E8%89%B2%E7%9A%84%E5%B0%B1%E6%98%AF%E4%B8%BAhellp%E8%A7%86%E5%9B%BE%E9%85%8D%E7%BD%AE%E7%9A%84%E8%B7%AF%E7%94%B1%E3%80%82(r">上邊第二行紅色的就是為hellp視圖配置的路由。(r'^hello/',hello),r表示忽略轉義字元,與C#中的@類似的含義。紅色部分表示浏覽器的位址,這裡是正則支援。通過正規表達式來比對浏覽器位址。然後如果比對位址成功,則把此位址的請求路由到藍色的部分的視圖。即,如果浏覽器中通路hello,那會比對到hello視圖。注意的是,因為要用到views.py中的hello函數,是以要先加載views.py子產品。即代碼中的第一行紅色的。</a>
3 浏覽器中通路
浏覽器中輸入http://127.0.0.1:8000/hello
即可看到hello world字樣。
4 傳回伺服器時間的頁
同上,自己想下,從浏覽器通路time。那要有個time的比對正則,即(r'^time/$',current_datetime),紅色部分。就是在浏覽器中輸入time後,應該能找到與之比對的路由。如果找到這個路由,應該調用一個視圖。這個視圖名可以随便命名,這裡命名為current_datetime。有了路由,現在開始定義current_datetime的視圖。
打開 views.py.建立立一個函數
def current_datetime(request):
now=datetime.datetime.now()
html="<thml><body>it is now %s.</body></html>" %now
return HttpResponse(html)
使用之前,先要導入datetime。
import datetime
然後,浏覽器中通路位址http://127.0.0.1:8000/time/
部落格園大道至簡
<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>
轉載請注明:部落格園