【问题标题】:VSTS PBI creation via Azure DevOps Python API通过 Azure DevOps Python API 创建 VSTS PBI
【发布时间】:2020-03-03 19:17:54
【问题描述】:

创建一个程序,该程序将在 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】:

    您可以同时使用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)
    

    【讨论】:

    • 第二个对我来说似乎工作得更好,但我认为我的网址不太正确。我的是一个“xxxllc-dev.visualstudio.com/”类型的链接。我不知道应该在哪里找到与您的链接相似的链接,但我认为它不应该是 azure.com。我这样想错了吗?
    • dev.azure.com 是新域名,但您仍然可以使用旧域名 visualstudio.com。请查看official document
    • 您需要刷新您的 azure devops 页面以显示新的工作项。
    • 是“?”在上面的 url wit?workitems 一个错字,或者它实际上在你的 url 中?也请尝试创建不同的工作项类型(即Bug)来检查它是否返回相同的结果。
    • 能否检查一下是否可以查看新创建的 PBI 的编辑页面。 '{org}.visualstudio.com/{project}/_workitems/edit/{PBI workitem id}/。您可以从发布请求响应中获取新创建的 PBI id。如果不。我建议您将此问题报告给Dev Community,并让微软开发团队检查您的项目。
    猜你喜欢
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多