import requests
import time


def wait_for_training(host_url, http_auth):
    """check every 5 seconds if the training has finished using the *finished* endpoint from the
    training service

    Returns
    -------
    finished : bool
        indicating if the training has finished successful

    """
    finished = False
    while not finished:
        try:
            print("Waiting for the training to be finished...")
            response = requests.get(
                '{0}/finished'.format(host_url), auth=http_auth, stream=True)
            res_json = response.json()
            if res_json['finished']:
                if response.status_code == 500:
                    raise Exception(res_json)
                finished = True
                print("Training finished")
                return finished
        finally:
            time.sleep(5)