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类。
本文详细介绍了Django框架中的HttpResponse类,包括其基本用法、如何通过构造函数传递字符串、逐步添加内容的方法以及如何使用迭代器来填充响应。对于需要流式传输响应的情况,推荐使用StreamingHttpResponse类。
1000

被折叠的 条评论
为什么被折叠?



