-1

I need to wait for a successful response from the server within a certain time. The easiest way to do it:

def wait_for_response():
    response = None
    time = 60
    while time > 0:
        response = requests.get(url=some_url)
        if response:
            break
        time.sleep(5)
        time -= 5
    if not response:
        print("SOME ERROR")
    return response.json()

But i don't think this solution is good. Is there any other better solution? Please note that the program should continue its work only after the function has finished its work

Pikachu
  • 309
  • 4
  • 14
  • 1
    Does this answer your question? [Timeout for python requests.get entire response](https://stackoverflow.com/questions/21965484/timeout-for-python-requests-get-entire-response) – Montgomery Watts Dec 25 '20 at 08:01
  • No. It says how long the answer should come. But in my case it is not the answer itself that is important, but its status.The answer may come immediately but his status could be 500 – Pikachu Dec 25 '20 at 08:12
  • I think this [advanced-usage-python-requests-timeouts-retries-hook](https://findwork.dev/blog/advanced-usage-python-requests-timeouts-retries-hooks/#combining-timeouts-and-retries) answers your question. – Albin Paul Dec 25 '20 at 08:20

2 Answers2

0

requests.get() is the function that waits for the request... The best you can do is put a timeout={seconds} argument to the function, like:

requests.get(some_url, timeout=60)

It will wait for 60 seconds for a request to be complete and then throw an error.

Suni
  • 118
  • 2
  • 7
  • I do not need to wait for the response from the server itself! I need to wait until the answer is good. For example, the answer from service can be 404. But i need to wait for a minute until the answer is 200 – Pikachu Dec 25 '20 at 20:54
  • Oopss.. It has to be `and int(time.time()-t) < timeout` – Suni Dec 25 '20 at 21:09
0

You can use this package https://pypi.org/project/backoff/

The on_exception decorator is used to retry when a specified exception is raised. Here’s an example using exponential backoff when any requests exception is raised:

@backoff.on_exception(backoff.expo,
                  requests.exceptions.RequestException)
def get_url(url):
return requests.get(url)
Wicky
  • 118
  • 2
  • 13