python - 在 Django 的 LiveServerTestCase 中使用 python-requests 失败,出现 502
问题描述
我正在尝试集成一个第 3 方应用程序,该应用程序使用 python-requests 来获取它从模板中解析的 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'
推荐阅读
- ssh - 当 X11 服务器死机时,ssh 上的 IPython 会话退出
- atom-editor - Atom Tex 编辑器无法安装任何软件包
- java - 如何在intellij中自动升级spring版本以及maven依赖项?
- timeout - JUnit5:DisableOnDebug 替换?
- c# - ASP Boilerplate 中的 LDAP 实现上的 InvalidCastException
- excel - 检查两列是否匹配,然后编辑一个单元格
- linux - 编译 coreutils 时出错 - 错误:函数可能是属性“const”的候选者 [-Werror=suggest-attribute=const]
- awk - 使用 AWK 将两个参数添加到双引号内的配置中
- swift - 在 NSCollectionViewItem 中重置的变量
- python - Lambda 函数不按位置顺序接受参数