Search code examples
pythonwhile-looppython-requestsgitlabgitlab-api

How to create loop for verification of status from http endpoint in python?


I have to create a verification of GitLab pipeline. I trigger pipeline, get its ID and then checking status of that specific pipeline. Requesting GitLab API Pipeline endpoint I'm getting some stages - "pending", "running" and afterwards "success" or "failed". I'm beginner with python. How can I retry that API call using python requests and get result only as "success" or "failed" ? I do have:

triggered_pipeline_id = "7532"
url = "{0}{1}".format(pipelineurl, triggered_pipeline_id)
response = requests.get(url=url, verify=False, headers=apidata)
raw_content = response.content.decode('UTF-8')
json_output = json.loads(raw_content)
returned_id = str(json_output["id"])
returned_status = str(json_output["status"])

This will give me immediately status - but it's "pending" or "running". After few seconds it has "success" or "failed". But rather than sleep for few seconds I guess it would be better to retry until response is "success" or "failed".

I thought that "while" loop would be best - but I'm not sure how to achieve that.

I have this in mind :

while (( returned_status == "pending" ) || ( returned_status == "running" )):
    time.sleep(5)

Is that correct or what should I do ? Thank you for your hints in advance :)


Solution

  • Provided the rest of your code is working...

    response = requests.get(url=url, verify=False, headers=apidata)
    json_output = response.json()
    returned_status = json_output["status"]
    
    while returned_status in ("pending", "running"):
        time.sleep(5)
    
        # repeat the request
        response = requests.get(url=url, verify=False, headers=apidata)
        json_output = response.json()
        returned_status = json_output["status"]
        
    # continue with the rest of your code
    print(returned_status)