使用Python调用Azure DevOps API无法从Azure Repos下载文件
问题原因
get_item_content() 方法返回的是流式响应的分片迭代生成器,不会自动聚合为完整文件内容,直接打印只会得到生成器的对象标识,不会触发实际的内容读取和文件下载。
解决方法
遍历生成器拉取所有内容分片,拼接后写入本地文件即可完成下载:
- 小文件场景可以先拼接全量内容再写入,代码逻辑简单直观
- 大文件场景建议边读取分片边写入磁盘,避免全量内容占用过高内存
参考实现代码
小文件版本
from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication import os personal_access_token = "MY_PAT" organization_url = "MY_ORGANIZATION_URL" repo_id = "MY_REPOSITORY_ID" file_path = "/FOLDER_NAME/FILE_NAME" save_local_path = os.path.basename(file_path) credentials = BasicAuthentication('', personal_access_token) connection = Connection(base_url=organization_url, creds=credentials) git_client = connection.clients.get_git_client() content_stream = git_client.get_item_content( repo_id, path=file_path, download=True, include_content=True ) # 拼接全量内容 file_bytes = b"".join(content_stream) # 写入本地 with open(save_local_path, "wb") as f: f.write(file_bytes) print(f"文件下载完成,保存路径:{os.path.abspath(save_local_path)}")
大文件优化版本
from azure.devops.connection import Connection from msrest.authentication import BasicAuthentication import os personal_access_token = "MY_PAT" organization_url = "MY_ORGANIZATION_URL" repo_id = "MY_REPOSITORY_ID" file_path = "/FOLDER_NAME/FILE_NAME" save_local_path = os.path.basename(file_path) credentials = BasicAuthentication('', personal_access_token) connection = Connection(base_url=organization_url, creds=credentials) git_client = connection.clients.get_git_client() content_stream = git_client.get_item_content( repo_id, path=file_path, download=True, include_content=True ) # 逐分片写入,不占大量内存 with open(save_local_path, "wb") as f: for chunk in content_stream: f.write(chunk) print(f"文件下载完成,保存路径:{os.path.abspath(save_local_path)}")
内容的提问来源于stack exchange,提问作者Grenston George
相关产品推荐
相关产品推荐

