从Google App engine调用Reddit api时出现错误429

2024-04-20 12:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在Google App Engine上运行cron一个多月了,没有任何问题。这项工作做了很多事情,一个是它使用urllib2调用从Reddit以及其他一些站点检索json响应。大约两周前,我开始在调用Reddit时看到错误,但在调用其他站点时没有错误。我收到的错误是HTTP错误429。

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

使用应用程序engine's interactive shell和以下代码时,您可以看到错误。

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代码,我不确定。 有什么想法吗?


Tags: 代码inpyjsonhttpdatabaselib
2条回答

Reddit速率对python shell的默认用户代理的api限制非常严格。您需要使用reddit用户名设置一个唯一的用户代理,如下所示:

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

关于reddit api的更多信息请参见https://github.com/reddit/reddit/wiki/API

Reddit可能正在计算基于IP的调用——这意味着GAE上共享IP的其他应用程序可能已经耗尽了配额。

如果你使用Reddit API密钥(我不知道他们是否发布了密钥),或者他们同意基于app头来限制API调用的速率,这可能会更好。

相关问题 更多 >