「生产环境一定要关 DEBUG」是常识,但关掉之后具体少了什么、多了什么?这篇把同一个项目在 DEBUG=True 和 False 下的 404 / 500 页面、SQL 记录、错误邮件和 runserver 的静态文件行为逐项对比。
DEBUG=True 不存在的路径 → 404 页面 2674 字节 标题: Page not found at /nope/ 含 card_number 的值: False 含异常文本: False
DEBUG=True 视图抛异常(局部变量 card_number) → 500 页面 51454 字节 标题: RuntimeError at /boom/ 含 card_number 的值: True 含异常文本: True
DEBUG=True 同上,@sensitive_variables("card_number") → 500 页面 56167 字节 标题: RuntimeError at /boom_sensitive/ 含 card_number 的值: True 含异常文本: True
DEBUG=False 不存在的路径 → 404 页面 179 字节 标题: Not Found 含 card_number 的值: False 含异常文本: False
DEBUG=False 视图抛异常(局部变量 card_number) → 500 页面 145 字节 标题: Server Error (500) 含 card_number 的值: False 含异常文本: False
DEBUG=False 同上,@sensitive_variables("card_number") → 500 页面 145 字节 标题: Server Error (500) 含 card_number 的值: False 含异常文本: FalseDEBUG=True 的技术页面对开发很有用,但它会把源码片段、局部变量、请求信息都展示出来,对外暴露就是信息泄漏。
页面里有 SECRET_KEY 这个名字: True | 含密钥原文: False | 含 ********************: True 页面里有「Settings」表: True | 含 ALLOWED_HOSTS 原值: True | 含数据库文件路径: True
Django 会把名字里有 KEY、SECRET、PASSWORD 等字样的设置脱敏,但其它设置(主机列表、路径)照样显示;局部变量更不会自动脱敏,要在 DEBUG=False 的错误报告里用 @sensitive_variables 才生效。
DEBUG=True 视图里做 50 次查询后 len(connection.queries) = 50 DEBUG=False 视图里做 50 次查询后 len(connection.queries) = 0
DEBUG=True 时每条 SQL 都留在内存里的 connection.queries,长时间运行的进程里会一直增长(本文只量了条数,没有量内存)。
DEBUG=True /boom/ 邮件数 0 主题 [] 正文含 card_number 的值: False DEBUG=True /boom_sensitive/ 邮件数 0 主题 [] 正文含 card_number 的值: False DEBUG=False /boom/ 邮件数 1 主题 ['[Django] ERROR (EXTERNAL IP): Internal Server Er'] 正文含 card_number 的值: False DEBUG=False /boom_sensitive/ 邮件数 1 主题 ['[Django] ERROR (EXTERNAL IP): Internal Server Er'] 正文含 card_number 的值: False
runserver DEBUG=True GET /static/hello.txt → 200
runserver DEBUG=False GET /static/hello.txt → 404
runserver DEBUG=False + --insecure GET /static/hello.txt → 200
[('security.W018', 'You should not have DEBUG set to True in deployment.')]DEBUG=False 后 runserver 不再提供静态文件,生产环境本来就该由 nginx / WhiteNoise / CDN 提供(第 132 篇)。