从Google App Engine调用Reddit API时出现错误429

8 投票
2 回答
8473 浏览
提问于 2025-04-17 10:51

我在Google App Engine上运行一个定时任务已经一个多月了,一直没有问题。这个任务做了很多事情,其中之一是用urllib2从Reddit和其他几个网站获取json格式的响应。大约两周前,我在调用Reddit时开始看到错误,但调用其他网站时没有问题。我收到的错误是HTTP错误429。

我尝试在Google App Engine之外执行相同的代码,结果没有问题。我也试过使用urlFetch,但还是收到了同样的错误。

你可以在这个应用的交互式命令行中使用以下代码看到这个错误。

import urllib2
data = urllib2.urlopen('http://www.reddit.com/r/Music/.json', timeout=60)

补充:我不明白为什么总是我出错而别人没问题。这是我收到的错误信息:

>>> import urllib2
>>> data = urllib2.urlopen('http://www.reddit.com/r/Music/.json', timeout=60)
Traceback (most recent call last):
  File "/base/data/home/apps/s~shell-27/1.356011914885973647/shell.py", line 267, in get
    exec compiled in statement_module.__dict__
  File "<string>", line 1, in <module>
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 400, in open
    response = meth(req, response)
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 429: Unknown

在应用引擎外运行的类似代码没有问题:

print urllib2.urlopen('http://www.reddit.com/r/Music/.json').read()

起初我以为是超时问题,因为之前是可以正常工作的,但现在不是超时错误,而是一个奇怪的HttpError代码,所以我不太确定。有什么想法吗?

2 个回答

0

有可能是Reddit在根据IP地址来计算请求次数。这意味着在同一个IP下的其他应用程序可能已经用完了配额。

如果你使用Reddit的API密钥(我不知道他们是否提供这种密钥),或者他们同意根据应用程序的标头来限制API请求次数,这种情况可能会有所改善。

14

Reddit 对于使用默认用户代理的 Python shell 的 API 限制得很严格。你需要设置一个独特的用户代理,其中包含你的 Reddit 用户名,像这样:

User-Agent: super happy flair bot by /u/spladug

关于 Reddit API 的更多信息可以在这里找到 https://github.com/reddit/reddit/wiki/API

撰写回答