首页 > 解决方案 > 如何在python中解决azure devop api Object Moved的结果

问题描述

当我更改了我的 blob 状态时,我尝试在 python 中使用 DevOps api 运行 Azure DevOps Pipeline。(所以..我的代码形式是 azure 函数的 blob 触发器形式)

import logging

import http.client
import mimetypes

import azure.functions as func

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import pprint

def main(myblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n"
                 f"Blob Size: {myblob.length} bytes")
    
    logging.info(f"start connect devops")
    conn = http.client.HTTPSConnection("dev.azure.com")
    body = "{\"previewRun\":false,\"stageToSkip=\": [],\"resources\": [], \"templateParameters\": [], \"variables\": []}"

    headers = {
        'Content-Type' : 'application/json',
        'Accept' : 'application/json',
        'Authorization' : 'Basic {Personal Access Token [String]}'
    }

    logging.info(f"try connect devops")
    conn.request("POST", "/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=6.0-preview.1", body, headers)
    res = conn.getresponse()
    logging.info(res.msg)
    data = res.read()
    logging.info(f"%s", data.decode("utf-8"))
    logging.info(f"finish connect devops")

我得到了这个结果。

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="https://spsprodea2.vssps.visualstudio.com/_signin?realm=dev.azure.com&amp;reply_to=https%3A%2F%2Fdev.azure.com%2Fgusrbs82mlops%2Ftestpipelinecall............">here</a>.</h2>
 </body></html>

“授权”:“基本 {个人访问令牌 [字符串]}”:我在 Azure Devops 中使用了我帐户的个人访问令牌

你能告诉我问题是什么吗?

标签: pythonazureazure-devopsazure-functionsazure-devops-rest-api

解决方案


官方文件

使用个人访问令牌

您应该将 PAT(个人访问令牌)转换为 base64 格式。

“授权”:“基本 {个人访问令牌 [字符串]}”

代码如下。

pat='lr***zcailq';
message_bytes = pat.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_pat = base64_bytes.decode('ascii')
url='https://dev.azure.com/jasonp2deploy/deployappwithvirtualapp/_apis/build/builds?api-version=5.0'
body = "{\"previewRun\":false,\"stageToSkip=\": [],\"resources\": [], \"templateParameters\": [], \"variables\": []}"
headers = {
    'Authorization' : 'Basic '+base64_pat
}
r = requests.get(url, data=json.dumps(body), headers=headers)
print(r.status_code)

结果

在此处输入图像描述


推荐阅读