【代理错误 django】Request error: HTTPSConnectionPool(host=‘‘, port=443): 、

发布于:2025-04-17 ⋅ 阅读:(27) ⋅ 点赞:(0)

❗问题 ❶:仍然是代理错误(ProxyError)

错误日志:

Request error: HTTPSConnectionPool(host='xueshu.baidu.com', port=443): Max retries exceeded ... Caused by ProxyError('Unable to connect to proxy', FileNotFoundError(2, 'No such file or directory'))

✅ 根本原因:

你当前 Python 环境 依旧在默认尝试走系统代理,即使你重启 Django,也还是报一样的错误。


✅ 解决方法:

请按照这个版本彻底修改 _fetch_and_parse

def _fetch_and_parse(self, url):
    import os
    # ✅ 清除环境变量代理
    os.environ.pop("HTTP_PROXY", None)
    os.environ.pop("HTTPS_PROXY", None)

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.3"
    }
    # ✅ 强制禁用代理
    response = requests.get(url, headers=headers, proxies={"http": "", "https": ""}, timeout=10)
    response.raise_for_status()
    response.encoding = 'utf-8'
    return BeautifulSoup(response.text, 'html.parser')

🔁 这个版本做了两件事:

  1. 显式删除系统代理环境变量(防止 requests 默认读取)
  2. 显式传入空代理地址 proxies={"http": "", "https": ""},防止 fallback 到默认代理设置

❗问题 ❷:你访问了一个 GET 方法,但只定义了 POST

错误日志:

PaperInfoView Method "GET" not allowed.

你定义的接口是这样的:

@action(methods=['post'], detail=False, url_path="fetch_paper_info")

只能支持 POST 请求。


✅ 解决方法:

选项一:使用 POST 请求(推荐)

前端或浏览器请求 URL 时 必须用 POST 请求

curl -X POST "http://localhost:8999/api/single/fetch_paper_info/?link=https://xueshu.baidu.com/usercenter/paper/show?paperid=xxx"
选项二:允许 GET(不推荐,但可用于调试)

你可以把方法改成:

@action(methods=['get', 'post'], detail=False, url_path="fetch_paper_info")

❗问题 ❸:你没有设置 serializer_class,导致 Django 报错

错误日志:

AssertionError: 'PaperInfoView' should either include a `serializer_class` attribute

✅ 解决方法:

即使你不序列化,也需要加一个空壳 serializer,否则 DRF 会报错。

from rest_framework import serializers

class DummySerializer(serializers.Serializer):
    pass

class PaperInfoView(CustomModelViewSet):
    serializer_class = DummySerializer

✅ 结论:你现在需要做 3 件事

步骤 操作
✅ 强制禁用代理 修改 _fetch_and_parseproxies={"http": "", "https": ""}os.environ.pop()
✅ 添加 serializer_class 加一个空的 DummySerializer
✅ 只用 POST 方式请求 或将 @action 改成支持 GET


网站公告

今日签到

点亮在社区的每一天
去签到