基于 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类。
相关文章推荐
- 基于 Django1.10 文档的深入学习(24)—— Form and field validation 之 cleaned_data
- 基于 Django1.10 文档的深入学习(17)——Customizing authentication 之 Custom users and permissions
- 基于 Django1.10 文档的深入学习(8)—— Model field reference 之 choices
- 基于 Django1.10 文档的深入学习(13)—— django.core.urlresolvers 之 reverse()
- 基于 Django1.10 文档的深入学习(18)—— Using the Django authentication system 之 LoginRequiredMixin
- 基于 Django1.10 文档的深入学习(30)——Class-based views
- 基于 Django1.10 文档的深入学习(9)—— Extra instance methods 之 get_FOO_display()
- 基于 Django1.10 文档的深入学习(21)——The Forms API 之 Form.errors
- 基于 Django1.10 文档的深入学习(27)—— django.conf.urls utility functions 之 url(),include(),static()
- 基于 Django1.10 文档的深入学习(23)—— QuerySet API reference 之 icontains
- 基于 Django1.10 文档的深入学习(25)—— Applications 之 基础部分
- 基于 Django1.10 文档的深入学习(3)—— models.py 之 FileField
- 基于 Django1.10 文档的深入学习(2)—— Settings.py 之 STATIC_*
- 基于 Django1.10 文档的深入学习(15)——django.contrib.auth.hashers
- 基于 Django1.10 文档的深入学习(28)—— Managing static files(e.g. images, JavaScript, CSS)
- 基于 Django1.10 文档的深入学习(6)—— Translation 之 short_description
- 基于 Django1.10 文档的深入学习(12)—— django.shortcuts 之 redirect()
- 基于 Django1.10 文档的深入学习(13)—— Making queries 之 Q objects
- 基于 Django1.10 文档的深入学习(10)—— django.contrib.auth 之 User model
- 基于 Django1.10 文档的深入学习(29)——Built-in Views 之 static.serve()