[英]Python exception for HTTP response codes
I'd like to raise a Python-standard exception when an HTTP response code from querying an API is not 200, but what specific exception should I use? 当查询API的HTTP响应代码不是200时,我想提出一个Python标准异常,但是我应该使用什么特定的异常? For now I raise an OSError: 现在我提出一个OSError:
if response.status_code != 200:
raise OSError("Response " + str(response.status_code)
+ ": " + response.content)
I'm aware of the documentation for built-in exceptions . 我知道内置异常的文档 。
You can simply call Response.raise_for_status()
on your response: 您只需在响应中调用Response.raise_for_status()
即可:
>>> import requests
>>> url = 'http://stackoverflow.com/doesnt-exist'
>>> r = requests.get(url)
>>>
>>> print r.status_code
404
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 831, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found
This will raise a requests.HTTPError
for any 4xx
or 5xx
response. 这将针对任何4xx
或5xx
响应引发requests.HTTPError
。
See the docs on Response Status Code for a more complete example. 有关更完整的示例,请参阅响应状态代码上的文档。
Note that this does not exactly do what you asked ( status != 200
): It will not raise an exception for 201 Created
or 204 No Content
, or any of the 3xx
redirects - but this is most likely the behavior you want: requests
will just follow the redirects, and the other 2xx
are usually just fine if you're dealing with an API. 请注意,这不正是你问什么( status != 200
这不会引发例外) 201 Created
或204 No Content
,或任何的3xx
重定向-但是这是最有可能你想要的行为: requests
将只需按照重定向,如果您正在处理API,其他2xx
通常就可以了。
The built-in Python exceptions are probably not a good fit for what you are doing. 内置的Python异常可能不适合您正在做的事情。 You will want to subclass the base class Exception
, and throw your own custom exceptions based on each scenario you want to communicate. 您将希望子类化基类Exception
,并根据您要通信的每个方案抛出自己的自定义异常。
A good example is how the Python Requests HTTP library defines its own exceptions : 一个很好的例子是Python Requests HTTP库如何定义自己的异常 :
In the event of a network problem (eg DNS failure, refused connection, etc), Requests will raise a
ConnectionError
exception. 如果出现网络问题(例如DNS故障,拒绝连接等),请求将引发ConnectionError
异常。In the rare event of an invalid HTTP response, Requests will raise an
HTTPError
exception. 在极少数情况下,HTTP响应无效,请求将引发HTTPError
异常。If a request times out, a
Timeout
exception is raised. 如果请求Timeout
则会引发Timeout
异常。If a request exceeds the configured number of maximum redirections, a
TooManyRedirects
exception is raised. 如果请求超过配置的最大重定向数,则会引发TooManyRedirects
异常。All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException
. Requests显式引发的所有异常都是从requests.exceptions.RequestException
继承的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.