Created
March 15, 2012 05:17
-
-
Save sparr/2042068 to your computer and use it in GitHub Desktop.
reddit api, post with retries and rate limit
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
def persistent_post_comment(parent,comment,retries=3,debug=False): | |
result = None | |
while retries >= 0: | |
try: | |
if debug: | |
print "debug: comment: " + comment | |
else: | |
print "comment: " + comment | |
result = post_comment(parent,comment) | |
except reddit.errors.RateLimitExceeded as e: | |
pprint.pprint(vars(e)) | |
print "Rate limited for " + str(e.sleep_time) + " seconds at " + time.strftime("%H:%M:%S", time.gmtime()) + ", sleeping" | |
time_left = e.sleep_time | |
while time_left > 0: | |
if time_left >= 60: | |
time.sleep(60) | |
time_left -= 60 | |
else: | |
time.sleep(time_left) | |
time_left = 0 | |
if time_left > 0: | |
print str(time_left) + " seconds left to sleep" | |
continue | |
except urllib2.HTTPError as e: | |
print e.__module__,'.',e.__class__.__name__,':',e | |
pprint.pprint(vars(e)) | |
print e.headers | |
print "code: " + str(e.code) | |
if e.code == 403: | |
print "HTTP 403, aborting this attempt" | |
return None | |
else: | |
print e.readlines() | |
print "retrying " + str(retries) + " more times, after 5 seconds" | |
time.sleep(5) | |
retries -= 1 | |
continue | |
except Exception as e: | |
print e.__module__,'.',e.__class__.__name__,':',e | |
pprint.pprint(dir(e)) | |
pprint.pprint(vars(e)) | |
print "retrying " + str(retries) + " more times, after 5 seconds" | |
time.sleep(5) | |
retries -= 1 | |
continue | |
break | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment