通过 Azure DevOps 创建 VSTS PBI Python API

VSTS PBI creation via Azure DevOps Python API

创建一个程序,该程序将在 AzureDevOps 中为我的组织自动创建 PBI。我不太明白如何制作引用 AzureDevOps 创建的 API 的脚本。我只是想让程序获取我的令牌并在 vsts 中创建一个工作项,然后使用自定义标题将其分配给自己。我已经安装了 azure CLI 并下载了 azure-devops-python-samples 文件,但是我没有一个很好的方法来引用 create_work_item 的方法。我想我需要一个关于如何使用 github files 的教程,并让另一个程序参考这种制作 PBI 的方法。我对这一切还很陌生,所以有人可以解释如何做到这一点真的很有帮助!

TLDR:A 点 - 将标题和 user_assignment 保存为另一个文件中的变量 B 点 - 参考这些变量并为我的组织制作 PBI。

我认为在这个问题中使用我的代码会很有帮助:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import json
import requests
#from bugcrowdapipull.py import xbug_title


pat = 'PAT HERE'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')

headers = {
    'Accept': 'application/json',
    'Authorization': 'Basic '+authorization
}
url="https://PROJECT.visualstudio.com/_apis/projects?api-version=5.1"

response = requests.get(url, headers=headers)

print(response)


def create_work_item(self, document, project, type='Bug', validate_only=None, bypass_rules=None, suppress_notifications=None, expand=None):
        """CreateWorkItem.
        [Preview API] Creates a single work item.
        :param :class:`<[JsonPatchOperation]> <azure.devops.v6_0.work_item_tracking.models.[JsonPatchOperation]>` document: The JSON Patch document representing the work item
        :param str project: Project ID or project name
        :param str type: The work item type of the work item to create
        :param bool validate_only: Indicate if you only want to validate the changes without saving the work item
        :param bool bypass_rules: Do not enforce the work item type rules on this update
        :param bool suppress_notifications: Do not fire any notifications for this change
        :param str expand: The expand parameters for work item attributes. Possible options are { None, Relations, Fields, Links, All }.
        :rtype: :class:`<WorkItem> <azure.devops.v6_0.work_item_tracking.models.WorkItem>`
        """
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if type is not None:
            route_values['type'] = self._serialize.url('type', type, 'str')
        query_parameters = {}
        if validate_only is not None:
            query_parameters['validateOnly'] = self._serialize.query('validate_only', validate_only, 'bool')
        if bypass_rules is not None:
            query_parameters['bypassRules'] = self._serialize.query('bypass_rules', bypass_rules, 'bool')
        if suppress_notifications is not None:
            query_parameters['suppressNotifications'] = self._serialize.query('suppress_notifications', suppress_notifications, 'bool')
        if expand is not None:
            query_parameters['$expand'] = self._serialize.query('expand', expand, 'str')
        content = self._serialize.body(document, '[JsonPatchOperation]')
        response = self._send(http_method='POST',
                              location_id='62d3d110-0047-428c-ad3c-4fe872c91c74',
                              version='6.0-preview.3',
                              route_values=route_values,
                              query_parameters=query_parameters,
                              content=content,
                              media_type='application/json-patch+json')
        return self._deserialize('WorkItem', response)


print('\n\n')

您可以同时使用 python api client library 和 Restful api 来创建工作项。请检查以下示例:

1、使用pythonapi客户端库。请检查 create_work_item 方法以获取更多信息。

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v5_1.py_pi_api import JsonPatchOperation

token = 'PAT'
team_instance = 'https://dev.azure.com/{OrganizationName}'
credentials = BasicAuthentication("", token)
connection = Connection(base_url=team_instance, creds=credentials)

wit_client = connection.clients.get_work_item_tracking_client()

def createworkitem():
    documents = []

    # add title field
    documents.append(JsonPatchOperation(from_=None,op='add',path="/fields/System.Title",value="i am created by python client"))
    # add assignTo field
    documents.append(JsonPatchOperation(from_=None,op='add',path="/fields/System.AssignedTo",value="User DisplayName"))

    result = wit_client.create_work_item(documents, "{ProjectName}", 'Product Backlog Item', validate_only=None, bypass_rules=None, suppress_notifications=None, expand=None)
    print(result)


if __name__ == "__main__":
   createworkitem()

2、使用Restful API、Work Item- Create

import requests
import base64

if __name__ == "__main__":

    pat = '{PAT}'
    authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')

    headers = {
    'Content-Type': 'application/json-patch+json', #specify the content-type
    'Authorization': 'Basic '+authorization
    } 

    url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/wit/workitems/$Product Backlog Item?api-version=5.1"

    body = [{
    "op": "add",
    "path": "/fields/System.Title",
     "value": "Sample from python api"
    },
    {
    "op": "add",
    "path": "/fields/System.AssignedTo",
     "value": "User Name"
    }]

    response = requests.post(url, json = body, headers=headers)