Django框架下在视图中使用模版的方法

yipeiwu_com5年前Python基础

 打开current_datetime 视图。 以下是其内容:

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 模板系统来修改该视图。 第一步,你可能已经想到了要做下面这样的修改:

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)

没错,它确实使用了模板系统,但是并没有解决我们在本章开头所指出的问题。 也就是说,模板仍然嵌入在Python代码里,并未真正的实现数据与表现的分离。 让我们将模板置于一个 单独的文件 中,并且让视图加载该文件来解决此问题。

你可能首先考虑把模板保存在文件系统的某个位置并用 Python 内建的文件操作函数来读取文件内容。 假设文件保存在 /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)

然而,基于以下几个原因,该方法还算不上简洁:

  •     它没有对文件丢失的情况做出处理。 如果文件 mytemplate.html 不存在或者不可读, open() 函数调用将会引发 IOError 异常。
  •     这里对模板文件的位置进行了硬编码。 如果你在每个视图函数都用该技术,就要不断复制这些模板的位置。 更不用说还要带来大量的输入工作!
  •     它包含了大量令人生厌的重复代码。 与其在每次加载模板时都调用 open() 、 fp.read() 和 fp.close() ,还不如做出更佳选择。

相关文章

Python实现文件信息进行合并实例代码

Python实现文件信息进行合并实例代码

将电话簿TeleAddressBook.txt和电子邮件EmailAddressBook.txt合并为一个完整的AddressBook.txt def main(): ftele...

python3中函数参数的四种简单用法

下面给大家介绍python3中函数参数的四种简单用法,具体内容如下所示: def print_two(*args): arg1, arg2 = args print "arg...

浅谈Python数据类型判断及列表脚本操作

浅谈Python数据类型判断及列表脚本操作

数据类型判断 在python(版本3.0以上)使用变量,并进行值比较时。有时候会出现以下错误: TypeError: unorderable types: NoneType() <...

Python实现图像几何变换

本文实例讲述了Python实现图像几何变换的方法。分享给大家供大家参考。具体实现方法如下: import Image try: im=Image.open('test.jpg')...

Python语言进阶知识点总结

Python语言进阶知识点总结

数据结构和算法 算法:解决问题的方法和步骤 评价算法的好坏:渐近时间复杂度和渐近空间复杂度。 渐近时间复杂度的大O标记: - 常量时间复杂度 - 布隆过滤器 / 哈希存储 - 对数时间复...