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

Python GET请求下载ZIP包无效问题排查求助

问题:Python脚本下载的ZIP包无效,curl可正常获取

我通过批处理调用Python脚本从仓库获取制品,调用命令固定为:

python get_artifacts.py %USERNAME%:%PASSWORD% http://url/artifactory/package.zip

使用的Python脚本如下:

import sys
import requests
from requests.auth import HTTPBasicAuth

def get_artifact(url, save_artifact_name, username, password, chunk_size=128):
    try:
        get_method = requests.get(url, 
                        auth = HTTPBasicAuth(username, password), stream=True)

        with open(save_artifact_name, 'wb') as artifact:
            for chunk in get_method.iter_content(chunk_size=chunk_size):
                artifact.write(chunk)

    except requests.exceptions.RequestException as error:
        sys.exit(str(error))

if __name__ == '__main__':

    username_and_password = sys.argv[1].split(':')
    username = username_and_password[0]
    password = username_and_password[1]

    url = sys.argv[2]
    save_artifact_name = url.split("/")[-1]

    print(f'Retrieving artifact {save_artifact_name}...')
    get_artifact(url, save_artifact_name, username, password)
    print("Finished successfully!")

目前脚本能完成下载,但得到的ZIP包无效,用curl执行相同操作却能获取有效包,需要排查问题。


排查与修复方案

以下是几个核心排查点及对应修复方式:

1. 未校验HTTP响应状态码

requests不会自动对非200类响应抛出异常,比如返回401未授权、404不存在或302重定向时,脚本会把错误页面的HTML内容写入ZIP文件,导致文件无效。
修复:在发起请求后立即校验状态码:

get_method = requests.get(url, auth=HTTPBasicAuth(username, password), stream=True)
get_method.raise_for_status()  # 新增该行,非200状态码直接抛出异常终止脚本

2. 密码含冒号导致拆分错误

如果密码里包含:,sys.argv[1].split(':')会把密码拆成多段,导致传入错误的认证信息,请求返回错误内容写入ZIP。
修复:限制只拆分一次,确保密码完整:

username_and_password = sys.argv[1].split(':', 1)  # 只按第一个冒号拆分
username = username_and_password[0]
password = username_and_password[1] if len(username_and_password) > 1 else ''

3. Chunk_size设置过小

当前chunk_size设为128字节,过小的块可能导致写入时出现拼接异常,或与部分仓库的流传输逻辑不兼容。
修复:调大chunk_size至合理值,比如1MB:

def get_artifact(url, save_artifact_name, username, password, chunk_size=1024*1024):
    # 其余代码保持不变

4. 重定向处理问题

部分仓库会返回重定向,curl默认自动跟随,但requests若遇到重定向后需要重新认证的场景,可能出现隐式失败。可以显式配置并确认:

get_method = requests.get(url, auth=HTTPBasicAuth(username, password), stream=True, allow_redirects=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:25:24