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

yipeiwu_com6年前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安装requests库的实例代码

requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多 因为是第三方库,所以使用前需要cmd安装 pip install requests 安装完...

python简单贪吃蛇开发

本文实例为大家分享了python简单贪吃蛇的具体代码,供大家参考,具体内容如下 import sys import random import pygame from pygame....

重命名批处理python脚本

将Copy of ********.bmp或者Copy of Copy of ********.bmp 此类文件统一命名为********0.bmp 或者********00.bmp等格式...

在Python中使用SQLite的简单教程

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。...

Python3+Appium实现多台移动设备操作的方法

需求: 连接本机的(两台安卓手机)或者本机安装的(安卓模拟器两个),实现同时安装本地apk包 。 demon.py 特别说明:必须写udid才能实现同时对两台以上的移动设备操作。对dev...