標籤:
3.Django動態網頁面
上一章節我們實現的helloworld視圖是用來示範Django網頁是建立的,它不是一個動態網頁,每次運行/helloworld/,我們都將看到相同的內容,它類似一個靜態HTML檔案。
接下來我們將實現另一個視圖,加入動態內容,例如當前日期和時間顯示在網頁上。通過簡單的下一步,來示範Django的這個技術。
3.1.一個簡單的動態網頁面例子
這個視圖做兩件事情: 擷取伺服器當前日期和時間,並返回包含這些值的HttpResponse 。為了讓Django視圖顯示當前日期和時間,在代碼中引入datetime模組,然後要把語句:datetime.datetime.now()放入視圖函數,然後返回一個HttpResponse對象即可。代碼如下:
from django.http import HttpResponseimport datetime def helloworld(request): return HttpResponse("Hello world") def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
函數的第二行代碼用 Python 的格式化字串(format-string)功能構造了一段 HTML 響應。 字串中的%s是預留位置,字串後面的百分比符號表示用它後面的變數now的值來代替%s。變數%s是一個datetime.datetime對象。它雖然不是一個字串,但是%s(格式化字串)會把它轉換成字串,如:2014-11-03 14:15:43.465000。這將導致HTML的輸出字串為:It is now 2014-11-03 14:15:43.465000。
完成添加views.py上述代碼之後,同上,在urls.py中添加URL模式,以告訴Django由哪一個URL來處理這個視圖。 如下:我們定義/mytime/URL:
from django.conf.urls import patterns, include, urlfrom mysite.views import hello,current_datetime # Uncomment the next two lines to enable the admin:# from django.contrib import admin# admin.autodiscover() urlpatterns = patterns(‘‘, # 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)), (‘^helloworld/$‘, hello), (‘^mytime/$‘, current_datetime),)
寫好視圖並且更新URLconf之後,運行命令python manage.py runserver運行伺服器,在瀏覽器中輸入http://127.0.0.1:8000, 我們將看到增加的mytime頁面目錄。
在瀏覽器中輸入http://127.0.0.1:8000/mytime/。 網頁將顯示當前的日期和時間。
3.2. 小結
本小節通過一個簡單例子展示了動態網頁面的例子,目前為止HTML源碼被直接寫入程式碼在 Python 代碼之中,下一章節我們將介紹Django模板系統,如何解決Python代碼與頁面設計分離的問題。
Python開發入門與實戰3-Django動態網頁面