django获取response响应头header信息判断返回内容类型

285 阅读1分钟

今天在写django中间件的时候需要判断返回类型的时候网上找不到有人碰到过这个问题,不知道怎么获取,通过找对象属性找出来了几种可以获取响应头信息的方法:

print(response._headers) # 下划线开头属于被保护的属性
{'content-type': ('Content-Type', 'application/json')}
(Pdb) print(type(response._headers))
<class 'dict'>

1.response.get('content-type') #此方法可以不区分大小写

(Pdb) print(response.get('CONTENT-TYPE'))
application/json
(Pdb) print(response.get('content-type'))
application/json

(Pdb) print(type(response.get('content-type')))
<class 'str'>

2.response._headers.get('content-type')

(Pdb) print(response._headers.get('content-type'))
('Content-Type', 'application/json')
(Pdb) print(type(response._headers.get('content-type')))
<class 'tuple'>

(Pdb) print(response._headers.get('CONTENT-TYPE'))
None
(Pdb) print(type(response._headers.get('CONTENT-TYPE')))
<class 'NoneType'>

3.response._headers['content-type']

(Pdb) p response
<Response status_code=200, "application/json">
(Pdb) p type(response)
<class 'rest_framework.response.Response'>

(Pdb) p response._headers['content-type']
('Content-Type', 'application/json')
(Pdb) p type(response._headers['content-type'])
<class 'tuple'>

4.最土的方法通过直接转换字符串判断:str(response)

(Pdb) print(str(response))
<JsonResponse status_code=200, "application/json">

感觉起来方法1是最方便不容易出问题的