Python django向self发送请求

Python django向self发送请求,python,django,Python,Django,有两次尝试从“正在工作”的django服务器获取响应。工作版本是硬编码的,在单元测试时不工作 # working # a = requests.post('http://localhost:8000/ImportKeys/', # data=json.dumps({'user_id': key_obj.email, #'key': self.restore_pubkey(key_obj.fingerprint)})) # not working a = r

有两次尝试从“正在工作”的django服务器获取响应。工作版本是硬编码的,在单元测试时不工作

# working
# a = requests.post('http://localhost:8000/ImportKeys/',
#                   data=json.dumps({'user_id': key_obj.email,
#'key': self.restore_pubkey(key_obj.fingerprint)}))

# not working

a = requests.post('http://' + request.get_host() + reverse('import_keys'),data=json.dumps({'user_id': key_obj.email,'key': self.restore_pubkey(key_obj.fingerprint)}))
在我不想开始工作的那个版本上,我得到了这个(end stacktrace):

文件“/home/PycharmProjects/lib/python3.4/site packages/requests/sessions.py”,第576行,在send中 r=适配器.send(请求,**kwargs) 文件“/home/PycharmProjects/lib/python3.4/site packages/requests/adapters.py”,第437行,在send中 raise ConnectionError(e,请求=请求) requests.exceptions.ConnectionError:HTTPConnectionPool(host='testserver',port=80):url:/ImportKeys超过了最大重试次数/(由NewConnectionError引起(':未能建立新连接:[Errno-2]名称或服务未知',))


是的,我看到它正在尝试连接到80端口,这是不好的。

要在
TestCase
类中测试您的视图,请使用,它是专门为此而设计的。如果您从
django.test.TestCase
继承测试用例,那么它已经通过
self.client
属性可用

class YourTestCase(TestCase):
    def test_import_keys_posting(self):
        data = {
            'user_id': key_obj.email,
            'key': self.restore_pubkey(key_obj.fingerprint)
        }
        response = self.client.post(reverse('import_keys'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {'result': 'ok'})

如果您使用Django REST框架,考虑使用它的奇妙之处,这就简化了API测试。

如果您需要在测试期间向服务器发送请求(在这种情况下,这可能不是来自测试代码本身,而是来自一些模拟或JS代码):

扩展
LiveServerTestCase
而不是
TestCase
。这将在测试期间启动实际服务器

如果在正在测试的常规代码中使用
request.build\u absolute\u uri()
,则需要更改测试代码以相应地更新HTTP请求头,如下所示:

checkout_url = '{}{}'.format(self.live_server_url, reverse('checkout', kwargs={'pk': article.id}))
parsed_url = parse.urlparse(self.live_server_url)

# add the info on host and port to the http header to make subsequent
# request.build_absolute_uri() calls work
response = self.client.get(checkout_url, SERVER_NAME=parsed_url.hostname, SERVER_PORT=parsed_url.port)

既然可以调用函数,为什么还要向self发送请求呢?这是测试用的吗?我想把视图“导入密钥”移动到分离服务。并且可能会从外部url获得结果。但现在,我只想通过url从“导入密钥”视图中获取结果。在测试中我遇到了一个问题。