You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9可正常发送GET请求,Django4.2+Python3.10请求失败求助

解决Python 3.10 + Django 4.2中requests请求出现ConnectionResetError(10054)的问题

在Python 3.9环境中执行以下HTTP GET请求可正常返回结果,但在基于Python 3.10的Django 4.2项目中运行相同代码时,抛出异常:('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

请求代码如下:

import requests
headersa = {
            'accept': 'text/plain',
            'x-api-key': 'pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp'
            }
url = "https://10.11.11.66:1003/config/v6/servers"
try:
    response = requests.get(url=url, headers=headersa, verify=False, timeout=50)
    print(response.text)
except requests.exceptions.RequestException as e:
    print("An error occurred:", e)

以下是针对性的解决方案:

  • 强制指定SSL/TLS版本
    Python 3.10默认的SSL/TLS配置比3.9更严格,部分老旧服务可能不兼容新版本协议。试试强制使用TLSv1.2:

    import requests
    from requests.adapters import HTTPAdapter
    from urllib3.poolmanager import PoolManager
    import ssl
    
    class TLSAdapter(HTTPAdapter):
        def init_poolmanager(self, connections, maxsize, block=False):
            self.poolmanager = PoolManager(
                num_pools=connections,
                maxsize=maxsize,
                block=block,
                ssl_version=ssl.PROTOCOL_TLSv1_2
            )
    
    headersa = {
                'accept': 'text/plain',
                'x-api-key': 'pgH7QzFHJx4w46fI~5Uzi4RvtTwlEXp'
                }
    url = "https://10.11.11.66:1003/config/v6/servers"
    
    session = requests.Session()
    session.mount('https://', TLSAdapter())
    try:
        response = session.get(url=url, headers=headersa, verify=False, timeout=50)
        print(response.text)
    except requests.exceptions.RequestException as e:
        print("An error occurred:", e)
    
  • 禁用HTTP/2协议
    Django 4.2环境中的requests可能默认启用HTTP/2,若目标服务器不支持该协议,会导致连接被重置。可以强制使用HTTP/1.1:

    # 直接在请求中添加参数
    response = requests.get(url=url, headers=headersa, verify=False, timeout=50, http2=False)
    
    # 或者通过Session全局配置
    session = requests.Session()
    session.mount('https://', HTTPAdapter(max_retries=3))
    response = session.get(url=url, headers=headersa, verify=False, timeout=50, http2=False)
    
  • 对齐依赖版本
    检查Python 3.9和Django 4.2环境中requests、urllib3、certifi等依赖的版本差异,新版本依赖的默认配置可能引发问题。可以降级到Python 3.9环境中可用的依赖版本:

    # 替换成你3.9环境里的requests版本号
    pip install requests==2.26.0
    
  • 排查网络环境差异
    Django项目部署的服务器可能有不同的防火墙规则或代理设置,导致连接被远程主机拦截。确认目标IP和端口在Django部署环境中可正常访问,没有被防火墙限制,也不存在代理配置冲突。

内容的提问来源于stack exchange,提问作者Bala Sundaram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:43:10