我正在尝试学习新闻源的 python api,所以我从这里复制了 python notebook 代码:source
当我运行代码时,除了 api 密钥外,完全按照发布的方式运行,我看到下面的错误(引用限制为 10)。即使我从 6 花费到 30 秒,它也会出现。我不确定为什么会出现这个错误,因为它没有出现在代码创建者身上(他们的整个回复都已发布)。抱歉我的愚蠢问题,我是新手。
This is my error message:
Working on ['2015-01-01', '00:00:00']...
Working on ['2015-02-01', '00:00:00']...
Working on ['2015-03-01', '00:00:00']...
Working on ['2015-04-01', '00:00:00']...
Working on ['2015-05-01', '00:00:00']...
Working on ['2015-06-01', '00:00:00']...
Working on ['2015-07-01', '00:00:00']...
Working on ['2015-08-01', '00:00:00']...
Working on ['2015-09-01', '00:00:00']...
Working on ['2015-10-01', '00:00:00']...
Working on ['2015-11-01', '00:00:00']... <-- Always stops here
in parse_response
{'fault': {'faultstring': 'Rate limit quota violation. Quota limit exceeded. 'detail': {'errorcode': 'policies.ratelimit.QuotaViolation'}}}
{'headline': [], 'date': [], 'doc_type': [], 'material_type': [], 'section': [], 'keywords': []}
网址对比:
在 nyt api 工作: https://api.nytimes.com/svc/archive/v1/2019/1.json?api-key=YOUR_API_KEY
即使我有权访问纽约时报存档,代码生成的 url 声明访问被拒绝:
https://api.nytimes.com/svc/archive/v1/2016-01-01/00:00:00.json?api-key=YOUR_API_KEY
'''fixed url new error message when running from python'''
超出 IOPub 数据速率。
notebook 服务器将暂时停止发送输出
到客户端以避免崩溃。
要更改此限制,请设置配置变量
--NotebookApp.iopub_data_rate_limit
。
当前值: NotebookApp.iopub_data_rate_limit=1000000.0(字节/秒) NotebookApp.rate_limit_window=3.0(秒)
但适用于浏览器:https://api.nytimes.com/svc/archive/v1/2016/1.json?api-key=YOUR_API_KEY
我看到其他人用谷歌问这个问题,但这是纽约时报。
谢谢
答案 0 :(得分:1)
确保无论是否引发 Exception
都等待:
def send_request(date):
'''Sends a request to the NYT Archive API for given date.'''
base_url = 'https://api.nytimes.com/svc/archive/v1/'
url = base_url + '/' + date[0] + '/' + date[1] + '.json?api-key=' + YOUR_API_KEY
try:
response = requests.get(url, verify=False).json()
except Exception:
return None
finally:
time.sleep(6)
return response
finally
子句是在 try
或 except
块完成之前执行的最后一个代码块。这意味着 finally
块将在 return
、try
或 except
(此处不适用)块中的任何 else
语句之前执行。这可能非常令人困惑。我建议在函数的末尾放置一个 return
语句,如下所示:
def send_request(date):
'''Sends a request to the NYT Archive API for given date.'''
base_url = 'https://api.nytimes.com/svc/archive/v1/'
url = base_url + '/' + date[0] + '/' + date[1] + '.json?api-key=' + YOUR_API_KEY
try:
response = requests.get(url, verify=False).json()
except Exception:
response = None
finally:
time.sleep(6)
return response
两者都会有相同的结果:无论响应如何都休眠六秒并返回 Response
或 None
,但我认为第二个更容易理解。现在,您仍然需要弄清楚 Exception
出现的原因并解决该问题。我建议在 print()
块中添加一些 except
调试语句以准确了解发生了什么。
另一种选择是假设读者完全理解 Python 的 try-except-else-finally 行为:
def send_request(date):
'''Sends a request to the NYT Archive API for given date.'''
base_url = 'https://api.nytimes.com/svc/archive/v1/'
url = base_url + '/' + date[0] + '/' + date[1] + '.json?api-key=' + YOUR_API_KEY
try:
return requests.get(url, verify=False).json()
except Exception:
return None
finally:
time.sleep(6)
这个 article 很好地解释了 Python 的 try-except-else-finally 行为。