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

如何用Python和Rest API自动化Azure DevOps的文件夹与文件创建?是否需Azure Automation?

Azure DevOps 文件夹与文件创建自动化:Python + REST API 实现指南

是否必须使用 Azure Automation?

不需要。Azure Automation 是一种托管式自动化服务,但你完全可以通过本地或服务器上的 Python 脚本,直接调用 Azure DevOps REST API 或使用官方 Python SDK 实现自动化操作,无需依赖 Azure Automation。

实现方式一:直接调用 Azure DevOps REST API

1. 准备个人访问令牌(PAT)

在 Azure DevOps 组织中生成 PAT,权限至少需要 Code (Read & Write),用于 API 请求认证。

2. 自动化创建文件夹

Git 本身不追踪空文件夹,因此创建文件夹的常规做法是向目标路径提交一个空的 .gitkeep 文件。示例代码:

import requests
from base64 import b64encode

# 替换为你的配置信息
org_name = "你的组织名"
project_name = "你的项目名"
repo_name = "你的仓库名"
pat = "你的PAT令牌"
folder_path = "docs/api-guides"  # 目标文件夹路径
target_branch = "refs/heads/main"

# 构建API请求URL
url = f"https://dev.azure.com/{org_name}/{project_name}/_apis/git/repositories/{repo_name}/pushes?api-version=7.1-preview.1"

# 生成认证头
auth = b64encode(f":{pat}".encode()).decode()
headers = {
    "Authorization": f"Basic {auth}",
    "Content-Type": "application/json"
}

# 构造请求体:提交.gitkeep文件
request_body = {
    "refUpdates": [
        {
            "name": target_branch,
            "oldObjectId": "0000000000000000000000000000000000000000"  # 首次提交用全0,后续提交填当前分支的commit ID
        }
    ],
    "commits": [
        {
            "comment": "Auto create folder via API",
            "changes": [
                {
                    "changeType": "add",
                    "item": {"path": f"/{folder_path}/.gitkeep"},
                    "newContent": {"content": "", "contentType": "rawtext"}
                }
            ]
        }
    ]
}

# 发送请求
response = requests.post(url, json=request_body, headers=headers)
response.raise_for_status()
print("文件夹创建完成:", response.json()["commits"][0]["commitId"])

3. 自动化创建文件

直接提交新文件到指定路径,示例代码:

import requests
from base64 import b64encode

# 替换为你的配置信息
org_name = "你的组织名"
project_name = "你的项目名"
repo_name = "你的仓库名"
pat = "你的PAT令牌"
file_path = "docs/api-guides/get-started.md"  # 目标文件路径
file_content = "# 快速入门指南\n这是通过API自动创建的文件内容"
target_branch = "refs/heads/main"

# 构建API请求URL
url = f"https://dev.azure.com/{org_name}/{project_name}/_apis/git/repositories/{repo_name}/pushes?api-version=7.1-preview.1"

# 生成认证头
auth = b64encode(f":{pat}".encode()).decode()
headers = {
    "Authorization": f"Basic {auth}",
    "Content-Type": "application/json"
}

# 构造请求体:提交新文件
request_body = {
    "refUpdates": [
        {
            "name": target_branch,
            "oldObjectId": "0000000000000000000000000000000000000000"
        }
    ],
    "commits": [
        {
            "comment": "Auto create file via API",
            "changes": [
                {
                    "changeType": "add",
                    "item": {"path": f"/{file_path}"},
                    "newContent": {"content": file_content, "contentType": "rawtext"}
                }
            ]
        }
    ]
}

# 发送请求
response = requests.post(url, json=request_body, headers=headers)
response.raise_for_status()
print("文件创建完成:", response.json()["commits"][0]["commitId"])

实现方式二:使用 Azure DevOps Python SDK

官方 SDK 封装了 API 调用逻辑,代码更简洁。先安装依赖:

pip install azure-devops

示例代码(同时创建文件夹和文件):

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v7_1.git.models import GitPush, GitCommit, GitChange, ItemContent, ItemContentType

# 替换为你的配置信息
org_url = "https://dev.azure.com/你的组织名"
pat = "你的PAT令牌"
project_name = "你的项目名"
repo_name = "你的仓库名"
target_branch = "refs/heads/main"

# 建立连接
credentials = BasicAuthentication("", pat)
connection = Connection(base_url=org_url, creds=credentials)

# 获取Git客户端
git_client = connection.clients.get_git_client()
repo = git_client.get_repository(repo_name, project_name)

# 定义文件夹创建操作(提交.gitkeep)
folder_change = GitChange(
    change_type="add",
    item={"path": "/docs/api-guides/.gitkeep"},
    new_content=ItemContent(content="", content_type=ItemContentType.RAWTEXT)
)

# 定义文件创建操作
file_change = GitChange(
    change_type="add",
    item={"path": "/docs/api-guides/get-started.md"},
    new_content=ItemContent(content="# 快速入门指南\nSDK自动创建的文件", content_type=ItemContentType.RAWTEXT)
)

# 准备提交和推送
commit = GitCommit(comment="Auto create folder and file via SDK", changes=[folder_change, file_change])
push = GitPush(
    ref_updates=[{"name": target_branch, "old_object_id": repo.default_branch.commit_id}],
    commits=[commit]
)

# 执行推送
result = git_client.create_push(push, repo.id, project_name)
print("操作完成,Commit ID:", result.commits[0].commit_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:01:29