Skip to content

Instantly share code, notes, and snippets.

@rduplain
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduplain/e09ad23eab067951ef60 to your computer and use it in GitHub Desktop.
Save rduplain/e09ad23eab067951ef60 to your computer and use it in GitHub Desktop.
Avoid race conditions by waiting for 200 OK on a URL.
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