首页 > 解决方案 > 在 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()

标签: pythondjangopython-requests

解决方案


我打算删除这个问题,但认为它可能对一些可怜的灵魂有用。事实证明,这个问题是由于请求尝试使用网络代理连接到 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'

推荐阅读