我正在尝试集成一个第三方应用程序,该应用程序使用python请求从模板中获取解析的URL。
我正在尝试使用LiveServerTestCase来测试集成。奇怪的是,curl可以工作,但请求测试test_requests_static_file
失败:
requests.exceptions.HTTPError: 502 Server Error: Connection refused for url: http://localhost:35819/static/testapp/style.css
有什么想法吗?
import subprocess
import requests
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
class LiveServerTests(StaticLiveServerTestCase):
def test_curl_static_file(self):
output = subprocess.check_output(["curl", '%s%s' % (self.live_server_url, '/static/testapp/style.css')])
self.assertIn('background: blue', output)
def test_requests_static_file(self):
response = requests.get('%s%s' % (self.live_server_url, '/static/testapp/style.css'))
response.raise_for_status()
我本来打算删除这个问题,但觉得它可能对一些可怜的人有用。事实证明,这个问题是由于请求试图使用网络代理来连接到localhost。
通过此测试验证:
from requests.utils import should_bypass_proxies as requests_should_bypass_proxies
class LiveServerTests(StaticLiveServerTestCase):
def test_requests_should_bypass_proxies_for_liveserver(self):
self.assertTrue(requests_should_bypass_proxies(self.live_server_url, None))
解决方案是使用NO_PROXY
环境变量。以下效果的东西会起作用:
import os
os.environ['NO_PROXY'] = 'localhost'