基于 Django1.10 文档的深入学习(14)—— Request and response objects 之 HttpResponse objects

来源:互联网 发布:手机淘宝一键秒杀在哪? 编辑:程序博客网 时间:2024/06/05 00:24

HttpResponse objects

class HttpResponse[source]

与由Django自动创建的HttpRequest对象相反,HttpResponse对象是您的责任。 您编写的每个视图都负责实例化,填充和返回HttpResponse。

HttpResponse类住在django.http模块中。

用法

传递字符串

典型的用法是将页面的内容作为字符串传递给HttpResponse构造函数:

>>> from django.http import HttpResponse>>> response = HttpResponse("Here's the text of the Web page.")>>> response = HttpResponse("Text only, please.", content_type="text/plain")

但是,如果要逐步添加内容,可以使用响应作为类似文件的对象:

>>> response = HttpResponse()>>> response.write("<p>Here's the text of the Web page.</p>")>>> response.write("<p>Here's another paragraph.</p>")

传递迭代器

最后,您可以将HttpResponse传递给迭代器而不是字符串。 HttpResponse将立即使用迭代器,将其内容存储为字符串,并将其丢弃。 具有close()方法(如文件和生成器)的对象将立即关闭。

如果您需要将响应从迭代器流式传输到客户端,则必须使用StreamingHttpResponse类。


0 0
原创粉丝点击