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

PythonAnywhere部署Flask应用时如何通过proxy.server:3128路由API GET请求

解决方案

PythonAnywhere免费套餐要求所有出站HTTP请求必须走官方提供的proxy.server:3128代理,你可以选择以下两种方式修改代码:

方案1(推荐):改用requests库简化代理配置

requests是比原生http.client更易用的HTTP请求库,代理配置非常简单,修改步骤如下:

  1. 先在你的PythonAnywhere虚拟环境中安装依赖:
pip install requests
  1. 修改请求代码:
from flask import Flask, request
import requests
import os

# 代理配置
PROXIES = {
    "http": "http://proxy.server:3128",
    "https": "http://proxy.server:3128"
}
# 替换为你自己的football-data API密钥,建议存环境变量读取
API_KEY = os.getenv("FOOTBALL_API_KEY", "你的实际API密钥")
HEADERS = {"X-Auth-Token": API_KEY}

def getCompetitions():
    print("running getCompetitions")
    resp = requests.get(
        "https://api.football-data.org/v2/competitions/",
        headers=HEADERS,
        proxies=PROXIES
    )
    # 直接调用json()方法解析返回结果,不需要手动解码
    return resp.json()

competitions = getCompetitions()

方案2:直接修改现有http.client代码适配代理

如果你不想更换依赖,可以按代理规则修改原生请求逻辑:

from flask import Flask, request
import http.client
import json
import os

API_KEY = os.getenv("FOOTBALL_API_KEY", "你的实际API密钥")
HEADERS = {"X-Auth-Token": API_KEY}

def getCompetitions():
    print("running getCompetitions")
    # 第一步:先连接代理服务器
    proxy_conn = http.client.HTTPConnection("proxy.server", 3128)
    # 第二步:向代理发起CONNECT请求,建立到目标站点的隧道
    proxy_conn.set_tunnel("api.football-data.org", 80)
    # 第三步:发送实际的GET请求
    proxy_conn.request("GET", "/v2/competitions/", None, HEADERS)
    response = json.loads(proxy_conn.getresponse().read().decode())
    proxy_conn.close()
    return response

competitions = getCompetitions()

额外注意事项

  • 调用前请确认api.football-data.org在PythonAnywhere的出站白名单中,如果不在可以在PythonAnywhere控制台提交白名单添加申请,一般1-2个工作日会审核通过。
  • 不要硬编码API密钥到代码中,推荐在PythonAnywhere的Web配置页添加环境变量存储密钥,用os.getenv读取更安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:18:03