Last active
August 29, 2015 14:06
-
-
Save rduplain/e09ad23eab067951ef60 to your computer and use it in GitHub Desktop.
Avoid race conditions by waiting for 200 OK on a URL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime as dt | |
import time | |
import requests # pip install requests | |
def get_ok(url): | |
"GET url and raise an exception if not 200 OK." | |
r = requests.get(url) | |
r.raise_for_status() | |
return r | |
def wait_for_url(url, timeout=120, sleep_period=0.15, opener=get_ok): | |
"Continue polling URL until 200 response or timeout (seconds) elapses." | |
expiration = dt.datetime.utcnow() + dt.timedelta(seconds=timeout) | |
while dt.datetime.utcnow() <= expiration: | |
try: | |
opener(url) | |
except Exception: | |
time.sleep(sleep_period) | |
else: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment