问题描述
根据 urllib2文档,
还有以下代码
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
引发代码201(已创建)的HTTPError:
raises an HTTPError with code 201 (created):
ERROR 2011-08-11 20:40:17,318 __init__.py:463] HTTP Error 201: Created
那为什么 urllib2
在成功的请求上抛出HTTPErrors?
So why is urllib2
throwing HTTPErrors on this successful request?
这不是很痛苦.我可以轻松地将代码扩展到:
It's not too much of a pain; I can easily extend the code to:
try:
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
except HTTPError, e:
if e.code == 201:
# success! :)
else:
# fail! :(
else:
# when will this happen...?
但是,根据文档和我无法找到有关此奇怪行为的类似问题的事实,这似乎不是预期的行为.
But this doesn't seem like the intended behavior, based on the documentation and the fact that I can't find similar questions about this odd behavior.
此外, else
块应该有什么期望?如果成功的状态码都被解释为 HTTPError
,那么什么时候> urllib2.urlopen()
只是返回一个普通的类似文件的响应对象,就像所有 urllib2
文档所引用的那样?
Also, what should the else
block be expecting? If successful status codes are all interpreted as HTTPError
s, then when does urllib2.urlopen()
just return a normal file-like response object like all the urllib2
documentation refers to?
推荐答案
实际的库文档中提到:
对于非200错误代码,这只是通过OpenerDirector.error()将作业传递给protocol_error_code处理程序方法.最终,如果没有其他处理程序处理该错误,则urllib2.HTTPDefaultErrorHandler将引发HTTPError.
For non-200 error codes, this simply passes the job on to the protocol_error_code handler methods, via OpenerDirector.error(). Eventually, urllib2.HTTPDefaultErrorHandler will raise an HTTPError if no other handler handles the error.
http://docs.python.org/library/urllib2.html#httperrorprocessor-objects
这篇关于为什么Python的urllib2.urlopen()为成功的状态码引发HTTPError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!