欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django框架下在視圖中使用模版的方法

 更新時(shí)間:2015年07月16日 11:56:41   投稿:goldensun  
這篇文章主要介紹了Django框架下在視圖中使用模版的方法,Django是Python豐富多彩的眾框架中最有人氣的一個(gè),需要的朋友可以參考下

 打開current_datetime 視圖。 以下是其內(nèi)容:

from django.http import HttpResponse
import datetime

def current_datetime(request):
  now = datetime.datetime.now()
  html = "<html><body>It is now %s.</body></html>" % now
  return HttpResponse(html)

讓我們用 Django 模板系統(tǒng)來修改該視圖。 第一步,你可能已經(jīng)想到了要做下面這樣的修改:

from django.template import Template, Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
  now = datetime.datetime.now()
  t = Template("<html><body>It is now {{ current_date }}.</body></html>")
  html = t.render(Context({'current_date': now}))
  return HttpResponse(html)

沒錯(cuò),它確實(shí)使用了模板系統(tǒng),但是并沒有解決我們在本章開頭所指出的問題。 也就是說,模板仍然嵌入在Python代碼里,并未真正的實(shí)現(xiàn)數(shù)據(jù)與表現(xiàn)的分離。 讓我們將模板置于一個(gè) 單獨(dú)的文件 中,并且讓視圖加載該文件來解決此問題。

你可能首先考慮把模板保存在文件系統(tǒng)的某個(gè)位置并用 Python 內(nèi)建的文件操作函數(shù)來讀取文件內(nèi)容。 假設(shè)文件保存在 /home/djangouser/templates/mytemplate.html 中的話,代碼就會像下面這樣:

from django.template import Template, Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
  now = datetime.datetime.now()
  # Simple way of using templates from the filesystem.
  # This is BAD because it doesn't account for missing files!
  fp = open('/home/djangouser/templates/mytemplate.html')
  t = Template(fp.read())
  fp.close()
  html = t.render(Context({'current_date': now}))
  return HttpResponse(html)

然而,基于以下幾個(gè)原因,該方法還算不上簡潔:

  •     它沒有對文件丟失的情況做出處理。 如果文件 mytemplate.html 不存在或者不可讀, open() 函數(shù)調(diào)用將會引發(fā) IOError 異常。
  •     這里對模板文件的位置進(jìn)行了硬編碼。 如果你在每個(gè)視圖函數(shù)都用該技術(shù),就要不斷復(fù)制這些模板的位置。 更不用說還要帶來大量的輸入工作!
  •     它包含了大量令人生厭的重復(fù)代碼。 與其在每次加載模板時(shí)都調(diào)用 open() 、 fp.read() 和 fp.close() ,還不如做出更佳選擇。

相關(guān)文章

最新評論