您的位置:首页 > 理论基础 > 计算机网络

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

2017-04-27 00:04 585 查看
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类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐