问答 跪求解决 python django.test Client () 报错解决方案

cmy514 · 2018年04月09日 · 最后由 cmy514 回复于 2018年04月09日 · 1212 次阅读

问题背景:
目前在使用 python 中的 django.test Client() 类进行客户端测试,遇到报错信息 ‘Invalid HTTP_HOST header: 'testserver'. You may need to add 'testserver' to ALLOWED_HOSTS.’ 报错,无法解决;

1、Django -v:1.10.3
2、python -v:python3
3、web 项目已经搭建成功:首页地址 http://127.0.0.1:8000/index/ 可正常访问;

使用 Django 内置 Client()类模拟 get() 和 post()请求方式进行客户端验证;

cmd.exe

from django.test import Client
c=Client()
response=c.get('/index')
运行到这步的时候,就报 ‘‘Invalid HTTP_HOST header: 'testserver'. You may need to add 'testserver' to ALLOWED_HOSTS’ 错误了

解决方法:

1、setting.py 中设置

DEBUG=True
ALLOWED_HOSTS = ['*'] / ALLOWED_HOSTS = ['127.0.0.1','localhost','testserver']

(因为看到网上说 当 DEBUG 为 True 并且 ALLOWED_HOSTS 为空时,主机将针对 ['localhost','127.0.0.1','[:: 1]'] 进行验证。)

DEBUG=False
ALLOWED_HOSTS = ['*'] / ALLOWED_HOSTS = ['127.0.0.1','localhost','testserver']

以上均无效。跪求大神帮忙解答,在线等…… 😭

共收到 1 条回复 时间 点赞

以上问题经过一上午的时间,还是没找到好的解决方案。但是我直接编写 TestCase 运行是没有问题,setting 中我也是保持
DEBUG=True
ALLOWED_HOSTS = [ ]

如上设置。

所以,如果有跟我一样在学习此部分的小伙伴遇到该问题,在调试的时候可以尝试略过。 只要关注 TestCase 运行结果就好。多谢给出意见的朋友,3Q。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册