通过Azure DevOps Python API创建VSTS PBI

通过Azure DevOps Python API创建VSTS PBI,python,azure,azure-devops,azure-api-apps,Python,Azure,Azure Devops,Azure Api Apps,创建一个程序,该程序将在AzureDevOps中为我的组织自动创建PBI。我不太明白如何引用AzureDevOps创建的API脚本。我只是想让程序获取我的令牌,在vsts中创建一个工作项,并使用自定义标题将其分配给我自己。我已经安装了azure CLI并下载了azure devops python示例文件,但对于我来说,没有一个好方法来引用创建工作项的方法。我想我需要一个教程,教我如何使用PBI,并简单地使用另一个程序引用。我对这一切都还不太熟悉,所以有人能解释一下如何做到这一点真的很有帮助 T

创建一个程序,该程序将在AzureDevOps中为我的组织自动创建PBI。我不太明白如何引用AzureDevOps创建的API脚本。我只是想让程序获取我的令牌,在vsts中创建一个工作项,并使用自定义标题将其分配给我自己。我已经安装了azure CLI并下载了azure devops python示例文件,但对于我来说,没有一个好方法来引用创建工作项的方法。我想我需要一个教程,教我如何使用PBI,并简单地使用另一个程序引用。我对这一切都还不太熟悉,所以有人能解释一下如何做到这一点真的很有帮助

TLDR:A点-将标题和用户分配保存为另一个文件中的变量 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')
#/usr/bin/env蟒蛇3
#-*-编码:utf-8-*-
导入base64
导入json
导入请求
#从bugcrowdapipull.py导入xbug_标题
帕特=‘帕特在这里’
authorization=str(base64.b64encode(字节(“:”+pat,“ascii”),“ascii”)
标题={
“接受”:“应用程序/json”,
“授权”:基本授权+授权
}
url=”https://PROJECT.visualstudio.com/_apis/projects?api-版本=5.1“
response=requests.get(url,headers=headers)
打印(答复)
def create_work_项(自我、文档、项目、类型='Bug',仅验证=None,绕过规则=None,禁止通知=None,扩展=None):
“”“CreateWorkItem。
[预览API]创建单个工作项。
:param:class:``document:表示工作项的JSON修补程序文档
:param str project:项目ID或项目名称
:param str type:要创建的工作项的工作项类型
:param bool validate_only:指示是否只想验证更改而不保存工作项
:param bool bypass_rules:不在此更新上强制执行工作项类型规则
:param bool suppress_通知:不为此更改触发任何通知
:param str expand:工作项属性的展开参数。可能的选项为{None、Relations、Fields、Links、All}。
:rtype::类:``
"""
路由_值={}
如果项目不是无:
路由_值['project']=self._serialize.url('project',project',str'))
如果类型不是“无”:
路由_值['type']=self._serialize.url('type',type,'str'))
查询_参数={}
如果validate_only不是None:
query_参数['validateOnly']=self.\u serialize.query('validate_only',validate_only',bool'))
如果绕过规则不是无:
查询_参数['bypassRules']=self._serialize.query('bypass_rules',bypass_rules',bool'))
如果“禁止通知”不是“无”:
query_参数['suppressNotifications']=self._serialize.query('suppress_notifications','suppress_notifications','bool'))
如果expand不是None:
query_参数['$expand']=self._serialize.query('expand',expand',str'))
content=self.\u serialize.body(文档“[JsonPatchOperation]”)
response=self.\u send(http\u method='POST',
位置_id='62d3d110-0047-428c-ad3c-4fe872c91c74',
version='6.0-preview.3',
路由_值=路由_值,
查询参数=查询参数,
内容=内容,
媒体(type='application/json补丁+json')
返回self.\u反序列化('WorkItem',response)
打印('\n\n')
您可以同时使用和Restful api来创建工作项。请查看以下示例:

1、使用python api客户端库。请检查方法以了解更多信息

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:


第二个对我来说似乎更好,但我认为我的url不太正确。我的链接是“xxxllc-dev.visualstudio.com/”类型的链接。我不知道我应该在哪里找到与你类似的链接,但我不认为它应该是azure.com。我这样想是不是错了?dev.azure.com是新域名,但您仍然可以使用旧域名visualstudio.com。请查看您需要刷新azure devops页面以显示新的工作项。上面url
wit?工作项中的“?”是打字错误,还是实际上在您的url中?还请尝试创建不同的工作项类型(即Bug),以检查它是否返回相同的结果。是否可以检查您是否可以查看新创建的PBI的编辑页面<代码>'{org}.visualstudio.com/{project}/_workitems/edit/{PBI workitem id}/
。您可以从post请求响应中获取新创建的PBI id。如果没有。我建议您将此问题报告给Microsoft开发团队,并让他们检查您的项目。
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)