[通过Azure DevOps Python API创建VSTS PBI

问题描述 投票:0回答:1

创建一个程序,该程序将为我的组织在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 azure azure-devops azure-api-apps
1个回答
1
投票

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

1,使用python api客户端库。请检查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)
© www.soinside.com 2019 - 2024. All rights reserved.