【发布时间】:2016-10-23 23:29:53
【问题描述】:
我正在尝试使用托管在 Google App Engine 上的 Django 应用程序中的 Shopify API。
对于我的本地单线程脚本,我使用modified version of this 以确保我不会超出 Shopify 的速率限制:
# Setup local bucket to limit API Calls
bucket = TokenBucket(40, .5)
api_call_success = False
while not api_call_success:
if bucket.tokens < 1:
sleep(.5)
else:
[... do an API call ...]
bucket.consume(1)
api_call_success = True
这适用于我的本地脚本,但不适用于我的 Google App Engine 托管应用程序,其中可能有多个租户,并且同时发生多个会话。
我一直在尝试研究处理这种速率限制的最佳方法,并且目前将尝试不断将每个用户/商店的请求响应标头写入 memcache,以便我可以随时检查'x-shopify-shop- api-call-limit' 查看之前的通话限制(和通话时间)是多少。所以我尝试了这样的事情:
fill_rate = .5
capacity = 40
# get memcache key info
last_call_time = memcache.get(memKey+"_last_call_time")
last_call_value = memcache.get(memKey+"_last_call_value")
# Calculate how many tokens should be available
now = datetime.datetime.utcnow()
delta = fill_rate * ((now - last_call_time).seconds)
tokensAvailable = min(capacity, delta + last_call_value)
# Check if we can perform operation
if tokensAvailble > 1:
[... Some work involving Shopify API call ...]
# Do some work and then update memcache
memcache.set_multi( {"_last_call_time": datetime.datetime.strptime(resp_dict['date'], '%a, %d %b %Y %H:%M:%S %Z'), "_last_call_value": resp_dict['x-shopify-shop-api-call-limit'].split('/',1)[0]}, key_prefix=memKey, time=120)
else:
[... wait ...]
谁能推荐一个更好的方法来管理这个速率限制?
【问题讨论】:
标签: python django google-app-engine shopify