[Tutor] URL test function.
Steven D'Aprano
steve at pearwood.info
Sat Oct 23 02:45:47 CEST 2010
On Sat, 23 Oct 2010 01:54:47 am Jeff Honey wrote:
> def is_ready():
> with settings(
> warn_only=True
> ):
> try:
> urllib2.urlopen('http://'+env.host_string+'\:8080')
> except urllib2.URLError:
> time.sleep(10)
> urllib2.urlopen('http://'+env.host_string+'\:8080')
That will only try twice, then give up with an exception.
> I am trying to get the 'host_string' environment variable to plug in
> here but not sure if the parent function will pass along that
> information nor if I can call it like this.
Have you tried it to see what happens?
> Additionally, I have
> never used try/except so I don't know if this will just try twice and
> quit. As it is now, it raises URLError and bombs out.
What does the error say?
I would try something like this:
def urlopen_retry(url, maxretries=10, time_to_wait=10):
"""Call urlopen on a url. If the call fails, try again up to a
maximum of maxretries attempts, or until it succeeds. Delay
between attempts by time_to_wait seconds, increasing each time."""
if maxretries < 1:
return None
for i in range(maxretries):
try:
return urllib2.urlopen(url)
except urllib2.URLError:
# Delay by (e.g.) 10 seconds, then 20, then 30, then ...
time.sleep(time_to_wait*(i+1))
raise # re-raise the last exception
and then call it with:
def is_ready():
url = 'http://' + env.host_string + '\:8080'
with settings(warn_only=True):
return urlopen_retry(url)
Hope this helps.
--
Steven D'Aprano
More information about the Tutor
mailing list