Python Google API资源限制错误
我理解资源的限制,你可以等它出来再去。 所以我编写了一个代码,运行到达到限制,然后等待6分钟,再次运行,等等,只是为了测试时间限制 有时候6分钟就够了,有时候不行。我需要一个一致的方法来突破这个资源限制Python Google API资源限制错误,python,python-2.7,api,google-api,Python,Python 2.7,Api,Google Api,我理解资源的限制,你可以等它出来再去。 所以我编写了一个代码,运行到达到限制,然后等待6分钟,再次运行,等等,只是为了测试时间限制 有时候6分钟就够了,有时候不行。我需要一个一致的方法来突破这个资源限制 counter=0 try: for i in range(5000): # high enough to break limit client.open(google_sheet).sheet1 counter+=1 sleep(.02)
counter=0
try:
for i in range(5000): # high enough to break limit
client.open(google_sheet).sheet1
counter+=1
sleep(.02)
print counter
except Exception as e:
print "ERROR"
if re.search('"code": 429', str(e)): #confirms error is due to resource limit
sleep(360)
for i in range(5000):
sheets_of_months[1].sheet_object
counter+=1
sleep(.02)
print counter
我让它运行,直到出现错误,等待6分钟,再次运行。打印只是为了避免无意义的等待
感谢阅读,感谢所有回复 谷歌建议的管理配额限制的方法是使用。我建议您(通过谷歌)查看此文档:
- (不再维护,但仍然良好)
import tenacity
# Wait 2^x * 0.5 seconds between each retry, up to 60 seconds
# 60 seconds afterwards.
# Stops after 30 attempts
@tenacity.retry(stop=tenacity.stop_after_attempt(30),
wait=tenacity.wait_exponential(multiplier=0.5, max=60))
def call_with_exponential_backoof(client, google_sheet):
client.open(google_sheet).sheet1
好吧,我想出来了,在仔细阅读之后,给不同的代码运行几个小时。当我注意到谷歌的帖子前后不一致时,我真的帮了大忙。但答案指出了一些我需要思考的问题 “算法的重要部分在于其指数性,而不是尝试次数。” 谷歌的医生说在16秒后停止并记录下来 所以我尝试了一些答案
times_page_opened=0
amount_of_seconds_iterating= 2
while True:
counter=0
try:
for i in range(5000):
counter+=1
if counter==2: # This confirms that it has opened a page again at least once already, meaning the limit has reset.
print "Had to wait %s seconds" % (amount_of_seconds_iterating) # This prints the amount of seconds in the iteration that it took.
amount_of_seconds_iterating= 2 # This just resets the iteration to 2 seconds for next time.
client.open(google_sheet).sheet1 # This just opens the actual page.
times_page_opened+=1
sleep(.02)
print times_page_opened # This helps me keep track of how many times the code has succesfully opened the page.
except Exception as e:
print "ERROR" # Tells me the code is waiting because it hit the error.
amount_of_seconds_iterating*=2 # Doubles the waiting time.
try:
if re.search('"code": 429', str(e)): # Confirms that it is infact the resource limit error.
sleep(amount_of_seconds_iterating)
client.open(google_sheet).sheet1 # Attempts again to re-open the page.
except:
print "Double Error"
一旦实现和简化,它看起来是这样的
def reset_limit():
iteration= 2
while True:
try:
client.open('Chem Sheet Summary Report DO NOT DELETE').sheet1
return
except:
iteration*=2
sleep(iteration)
为了使用它,我会尝试执行我将遇到的任何操作,如果它达到资源限制,它将调用reset_limit函数,该函数将仅在资源限制重置后返回,如下所示
while True:
try:
client.open(google_sheet).sheet1
except Exception as e:
if re.search('"code": 429', str(e)):
reset_limit()
可悲的是,我已经阅读并实现了谷歌的指数退避,但它没有帮助,这是因为我的配额限制应该是每100秒一次。但是,当我等待超过6分钟时,它有时仍然不起作用。我已经尝试添加随机的毫秒数,遗憾的是没有区别。我尝试用一个使用坚韧的例子来改进我的答案。