django的视图函数都要返回一个httpresponse对象,httpresponse存在于django.http模块中
1.将页面的内容当做一个string,传到httpresponse
>>>from django.http import HttpResponse
>>>response = HttpResponse('this is a test')
>>>response = HttpResponse('this is a file', content_type='application/text')
2.把httpresponse当做file-like object 使用
>>>response = HttpResponse()
>>>response.write("<p>Here's the text of the Web page.</p>")
>>>response.write("<p>Here's another paragraph.</p>")
3.你也可以给httpresponse传一个iterator. 当你给httpresponse传递一个iterator时, 它会立即使用这个iterator, 把它存储为一个string, 然后丢弃这个iterator. 如果你想把iterator中的内容作为流,传入到客户端中,你需要使用StreamingHttpResponse
4.设置response的header字段
你可以把response当做一个字典来删除,添加header字段
>>>response = HttpResponse()
>>>response['Age'] = 20
>>>del response['Age']
5.告诉浏览器把response当做一个附件
>>>response = HttpResponse(my_data, content_type='application/vnd.ms-excel')
>>>response['Content-Disposition'] = 'attachment; filename="foo.xls" '
6.属性
HttpResponse.content
一个二进制字符串
HttpResponse.charset
字符集编码格式
HttpResponse.status_code
response的状态码
HttpResponse.closed
如果response结束了,返回True