Django--httpResponse 头部的问题

2017-04-27 16:58:43 +08:00
 ray1888
刚刚去看了 DJango http 的 Response 的源码,但是好像没看到头部内容组装的部分,那有大神能够解答它 Response 头部的参数是那里来的吗?感谢万分
3261 次点击
所在节点    Python
10 条回复
blackeeper
2017-04-27 18:27:00 +08:00
![B31ED17C-3638-423C-B7E1-EFF88C08ED64.png]( https://ooo.0o0.ooo/2017/04/27/5901c75e7dfb5.png)
eehello
2017-04-27 18:46:12 +08:00
@blackeeper 请问用的什么软件?
blackeeper
2017-04-27 20:41:51 +08:00
@eehello dash
eehello
2017-04-27 22:10:56 +08:00
@blackeeper 谢谢。
😅😅😅表示没有 mac,只能看着眼馋😍😍😍
blackeeper
2017-04-27 22:24:18 +08:00
@eehello windows 也有类似的,你可以试试这个 https://zealdocs.org/
ray1888
2017-04-27 22:43:02 +08:00
@blackeeper 我的意思是你 Header 这里不是空的吗?但是最后 response 出来 header 有东西的,那些是在哪里填写的
IanPeverell
2017-04-28 10:26:27 +08:00
@ray1888 这部分你可以看源码,是后面设置了__setitem__函数加上去的,参数包括 header,value,先把 header 和 value 用内建的函数重新编码,然后一次性加入_header 字典中,接着是 serialize_headers 函数获取 header 以 bytestring 的格式传给__bytes__或者__str__,然后通过 setdefault 函数设置默认 header 如果预先没有设置 header。

以上就是我从 Django 的源码得到的部分,如果有误请指正
eehello
2017-04-28 12:29:30 +08:00
@blackeeper 非常感谢
ray1888
2017-04-28 17:38:30 +08:00
@IanPeverell

其实在这个地方还是没有写

def _convert_to_charset(self, value, charset, mime_encode=False):
"""
Convert headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, apply MIME-encoding.
"""
if not isinstance(value, (bytes, str)):
value = str(value)
if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
isinstance(value, str) and ('\n' in value or '\r' in value)):
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
try:
if isinstance(value, str):
# Ensure string is valid in given charset
value.encode(charset)
else:
# Convert bytestring using given charset
value = value.decode(charset)
except UnicodeError as e:
if mime_encode:
value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
else:
e.reason += ', HTTP response headers must be in %s format' % charset
raise
return value

def __setitem__(self, header, value):
header = self._convert_to_charset(header, 'ascii')
value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
self._headers[header.lower()] = (header, value)

所以他默认 header 还是空的,只要你不创建 response 实例时候没有初始化 header,所以还是没有解答我的问题,因为一般都是使用 render_to_response 或者 response 直接创建相应的,但是 header 我们一般都没有填充,那到底是哪里填充的(就是在哪里实例化的时候框架帮我们填了 header 我还是没有找到)
blackeeper
2017-04-28 20:28:18 +08:00
这个是 Django 的中间件自动来帮我们填充的 header,比如说你在 settings 文件没有添加了 DEFAULT_CONTENT_TYPE,也没用在其它地方配置,那么中间件自动就填充。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/357751

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX