HttpResponse 對象
. 使用字符串 或者 bytestring去構(gòu)造HttpResponse滥玷。
. 如果需要向HttpResponse添加內(nèi)容, 則通過如下方式:
response = HttpResponse()
response.write(“<p>Here’s the text of the web page.</p>”)
response.write(“<p>Here’s another paragraph.</p>”)
. 去除response頭部中的某些字段
response = HttpResponse()
response[‘Age’] = 120
del response[‘Age’] #注意當(dāng)key不存在時 也不會引起KeyError
. 設(shè)置Cache-Control 和 Vary頭部字段咪笑,可以使用patch_cache_control() 和 patch_vary_headers() 方法
. HTTP頭部字段值不能包含新行(CR/LF), 否則會出現(xiàn)BadHeaderError
. 告訴瀏覽器返回的是文件附件犯祠,可以像下面這樣做:
// 1.需要指定content_type; 2.需要設(shè)置Content-Disposition頭
response = HttpResponse(my_data, content_type=‘a(chǎn)pplication/vnd.ms-excel’)
response[‘Content-Disposition’] = ‘a(chǎn)ttachment;filename=“foo.xls”’
HttpResponse的屬性
.content bytestring類型
.charset response的編碼方式
如何實例化HttpResponse的時候沒有指定charset豆瘫,則使用content_type中的,如果還不行偷俭,則使用DEFAULT_CHARSET中的設(shè)置浦箱。
.status_code
.reason_phrase
.streaming 設(shè)置為True時,中間件會區(qū)別對待streaming responses和常規(guī)的responses
.closed
HttpResponse的方法
.__init__(content=b’’, content_type=None, status=200, reason=None, charset=None)
.__setitem__(header, value) 設(shè)置頭部信息 key和value都是字符串
.__delitem__(header) 大小寫敏感
.__getitem__(header)
.__has_header(header)
.setdafault(header, value) 設(shè)置header的默認(rèn)值
.set_cookie(key, value=‘’, max_age=None, expires=None, path=‘/’, domain=None, secure=None, httponly=False, samesite=None)
max_age是秒制妄;expires如果沒有指定的話 會自動計算
.set_sighed_cookied(key, value, salt=‘’, max_age=None, expires=None, path=‘/’, domain=None, secure=None, httponly=False, samesite=None)
HttpResponse子類 用于處理不同類型的http responses
- HttpResponseRedirect
- HttpResponsePermanentRedirect
- HttpResponseNotModified
- HttpResponseBadRequest
- HttpResponseNotFound
- HttpResponseForbidden
- HttpResponseNotAllowed
- HttpResponseGone
- HttpResponseServerError
JsonResponse對象
構(gòu)造函數(shù)
JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
StreamingHttpResponse 對象
用于從django向瀏覽器 stream response
使用場景:當(dāng)生成response需要長時間或大內(nèi)存時掸绞,可以使用;例如生成一個csv文件
FileResponse 對象
FileResponse(open_file, as_attachment=False, file-name=‘’, **kwargs)