视图返回的 HttpResponse 到底带哪些头?JsonResponse 会怎么序列化 datetime、Decimal?头部能不能被注入换行?这篇不看文档,把这些行为一条条试出来。
status 200 Content-Type: text/html; charset=utf-8 Content-Length: 5 charset = utf-8
视图只返回 HttpResponse('hello'),得到的 Content-Type 带 charset。Content-Length 不是 HttpResponse 自己算的(见第五节)。
{'Content-Type': 'text/html; charset=utf-8', 'x-custom': 'b', 'X-Other': '1', 'Content-Length': '1'}
r['X-Custom'] = b r['x-CUSTOM'] = b
Set-Cookie: Set-Cookie: sid=abc; expires=Wed, 30 Sep 2026 12:00:43 GMT; HttpOnly; Max-Age=60; Path=/; SameSite=Lax
has_header("x-other") = Trueresponse.headers 是大小写不敏感的字典;重复赋值以最后一次为准。Cookie 通过 set_cookie 写入 Set-Cookie 头,可以直接指定 httponly、samesite、max_age。
Content-Type: application/json
body: {"when": "2026-01-02T03:04:05", "price": "9.90", "id": "00000000-0000-0000-0000-000000000001"}
safe=False 的列表: [1, 2, 3]
JsonResponse([1,2]) → TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
JsonResponse({set}) → TypeError: Object of type set is not JSON serializable默认序列化器是 DjangoJSONEncoder,认识 datetime、Decimal、UUID 等;它不认识 set。safe=True(默认)只允许 dict 作为顶层,列表要显式 safe=False——这是历史上防 JSON 劫持的保守选择(这一条来自文档说法,本文没有验证其安全性)。
BadHeaderError: Header values can't contain newlines (got 'a\r\nSet-Cookie: pwned=1')
值里带换行会立刻抛 BadHeaderError,而不是等到发送时。
无中间件: {'Content-Type': 'text/html; charset=utf-8'}响应阶段由 CommonMiddleware 加上。流式响应没有它(第 22 篇)。