-1

I have a case where I have to keep checking the response of a GET call until I see the status as success in the api response. And it takes around 20 to 50 mins to get the status from active to success. Only when I see this status I can perform my other action.

How can I achieve that in python?

I tried this polling python library. But it's not much of a help.

This is my code. But it's not working how I want. Is there any other way to do this?

    try:
        while True:
            response = requests.get(f'{os.environ["BASE_URL"]}/syncs/076532', headers=headers)
            json_res = response.json()
            if json_res.get('status') != 'success':
                logging.info("Polling started.......")
                logging.info("Waiting.......")
                time.sleep(120)
            print("Got status as success. Proceeding......")
            sys.exit()
    except KeyboardInterrupt:
        logging.info("exiting")
        sys.exit()

Thanks in Advance

amitesh shukla
  • 49
  • 1
  • 12
  • what doesn't it do that it should do? you can have several Except blocks for handling different exceptions (such as no JSON in response or a timeout) – ti7 May 23 '21 at 20:33
  • Oh, when you successfully read, you want to `break` or `return` then and otherwise continue in your `while` loop (such that a _new_ request is made each iteration, rather than just one at present .. this could be fixed via `continue` after sleeping) .. take a look at the docs [break and continue Statements, and else Clauses on Loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – ti7 May 23 '21 at 20:34

1 Answers1

1

You can try this:

def custom_request(url: str, headers: dict):
    if requests.get(url=url, headers=headers).json().get('status') != 'success':
        logging.info("Polling started.......")
        logging.info("Waiting.......")
        return False
    return True


def main():
    try:
        polling.poll(
            custom_request,
            step=60,
            args=(f'{os.environ["BASE_URL"]}/syncs/076532', headers),
            poll_forever=True
        )
        print("Got status as success. Proceeding......")
        exit()
    except KeyboardInterrupt:
        logging.info("exiting")
        exit()

What difficulties have you faced by using polling?

fabelx
  • 197
  • 1
  • 12
  • I got the answer. And my answer is derived from your answer. It's not totally the same as it's given. But it's similar to it. – amitesh shukla May 25 '21 at 10:22