我很难正确处理一些日期时间值。我们有一个SaaS提供商,它实现了他们的API,HTTP响应代码为429,这意味着我们已经超过了他们的速率,并要退出。他们传递了一个"X-RateLimit-Reset"的标头,其值是我们的请求重置时的ISO8601日期戳。我试着取这个值,然后取"现在",以秒为单位计算我需要等待多长时间。到目前为止,我已经构建了这个代码:
elif ask.status_code == 429:
print("API rate limit hit. Resting...")
# ask.headers['X-RateLimit-Reset'] is passed back with a ISO8601 time stamp of when the api limit will be reset.
# example: “2016-12-13T18:38:00Z”
a = time.strptime(ask.headers['X-RateLimit-Reset'], '%Y-%m-%dT%H:%M:%SZ')
a = time.mktime(a)
print(ask.headers['X-RateLimit-Reset'])
# I don't get this...
myTZ = datetime.tzinfo
myTZ.timezone.utc
# Calculate the offset taking into account daylight saving time
b = datetime.utcnow().replace(tzinfo=myTZ.timezone.utc).replace(microsecond=0).isoformat()
b = time.strptime(b, '%Y-%m-%dT%H:%M:%S%z')
b = time.mktime(b)
# Time in seconds to wait and retry
apiReset = (b-a)+1
print("Sleeping {} seconds".format(apiReset))
time.sleep(apiReset)
return self.CallAPI(uri, method, data, timeout)
它只是没有做我需要它做的事情。我已经忽略了一些例外,但现在我只能做一个:
API rate limit hit. Resting...
2018-12-18T00:07:54Z
Traceback (most recent call last):
File "Development/evident.io/mainbody.py", line 22, in <module>
EvidentIO.ListSubORGs()
File "/Users/i864248/OneDrive - SAP SE/Development/evident.io/evidentio.py", line 112, in ListSubORGs
return self.APICallHandler('/api/v2/sub_organizations')
File "/Users/i864248/OneDrive - SAP SE/Development/evident.io/evidentio.py", line 297, in APICallHandler
response = self.CallAPI(uri, method, data, timeout)
File "/Users/i864248/OneDrive - SAP SE/Development/evident.io/evidentio.py", line 407, in CallAPI
myTZ.timezone.utc
AttributeError: 'getset_descriptor' object has no attribute 'timezone'
有人能帮我吗?也许我从一开始就做得不对?
当然,在发布这篇文章后不久,我找到了一个不错的解决方案。使用其他地方的一些例子,我将代码简化为:
a = datetime.strptime(ask.headers['X-RateLimit-Reset'], '%Y-%m-%dT%H:%M:%SZ')
timestamp = (a - datetime(1970, 1, 1)).total_seconds()
ts = time.time()
timeDiff = (timestamp - ts)
print("Sleeping for {} seconds".format(timeDiff))
time.sleep(timeDiff + 1)
print("Continuing")
return self.CallAPI(uri, method, data, timeout)
这似乎很有效。