Django框架中render_to_response()函数的使用方法

yipeiwu_com5年前Python基础

通常的情况是,我们一般会载入一个模板文件,然后用 Context渲染它,最后返回这个处理好的HttpResponse对象给用户。 我们已经优化了方案,使用 get_template() 方法代替繁杂的用代码来处理模板及其路径的工作。 但这仍然需要一定量的时间来敲出这些简化的代码。 这是一个普遍存在的重复苦力劳动。Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。

该捷径就是位于 django.shortcuts 模块中名为 render_to_response() 的函数。大多数情况下,你会使用``\ ``````对象,除非你的老板以代码行数来衡量你的工作。

System Message: WARNING/2 (<string>, line 1736); backlink

Inline literal start-string without end-string.

System Message: WARNING/2 (<string>, line 1736); backlink

Inline literal start-string without end-string.

System Message: WARNING/2 (<string>, line 1736); backlink

Inline literal start-string without end-string.

下面就是使用 render_to_response() 重新编写过的 current_datetime 范例。

from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
 now = datetime.datetime.now()
 return render_to_response('current_datetime.html', {'current_date': now})

大变样了! 让我们逐句看看代码发生的变化:

    我们不再需要导入 get_template 、 Template 、 Context 和 HttpResponse 。相反,我们导入 django.shortcuts.render_to_response 。 import datetime 继续保留.

    在 current_datetime 函数中,我们仍然进行 now 计算,但模板加载、上下文创建、模板解析和 HttpResponse 创建工作均在对 render_to_response() 的调用中完成了。 由于 render_to_response() 返回 HttpResponse 对象,因此我们仅需在视图中 return 该值。

render_to_response() 的第一个参数必须是要使用的模板名称。 如果要给定第二个参数,那么该参数必须是为该模板创建 Context 时所使用的字典。 如果不提供第二个参数, render_to_response() 使用一个空字典。

相关文章

Python实现的生成格雷码功能示例

Python实现的生成格雷码功能示例

本文实例讲述了Python实现的生成格雷码功能。分享给大家供大家参考,具体如下: 问题 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Co...

Python下的常用下载安装工具pip的安装方法

1、pip下载安装 1.1 pip下载 # wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#...

Python 代码性能优化技巧分享

Python 代码性能优化技巧分享

如何进行 Python 性能优化,是本文探讨的主要问题。本文会涉及常见的代码优化方法,性能优化工具的使用以及如何诊断代码的性能瓶颈等内容,希望可以给 Python 开发人员一定的参考。...

python访问类中docstring注释的实现方法

本文实例讲述了python访问类中docstring注释的实现方法。分享给大家供大家参考。具体分析如下: python的类注释是可以通过代码访问的,这样非常利于书写说明文档 clas...

python实现将json多行数据传入到mysql中使用

将json多行数据传入到mysql中使用python实现 表需要提前创建,字符集utf8 如果不行换成utf8mb4 import json import pymysql def...