박현균
박현균

Reputation: 59

How to solve azure devop api Object Moved result in python

When i have changed my blob status, I trying Azure DevOps Pipeline run using DevOps api in python.(so.. my code form is azure function's blob trigger form)

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")

I got this result.

<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>

'Authorization' : 'Basic {Personal Access Token [String]}' : i used my account's Personal Access token in Azure Devops

Could you tell me what the problem is?

Upvotes: 1

Views: 1208

Answers (1)

Jason Pan
Jason Pan

Reputation: 21916

Offical Doc

Use personal access tokens

You should convert your PAT (Personal Access Token) to base64 format.

'Authorization' : 'Basic {Personal Access Token [String]}'

Code Like below.

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)

Result

enter image description here

Upvotes: 1

Related Questions