Python请求库异常处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24237185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:17:12  来源:igfitidea点击:

Python requests library Exception handling

pythonexceptionpython-requestshttp-status-code-503

提问by Frankline

I am creating a download service using the python requests library (See here) to download data from another server. The problem is that sometimes I get a 503 errorand I need to display an appropriate message. See sample code below:

我正在使用 python requests 库(请参阅此处)创建下载服务以从另一台服务器下载数据。问题是有时我会得到一个503 error,我需要显示一个适当的消息。请参阅下面的示例代码:

import requests
s = requests.Session()
response = s.get('http://mycustomserver.org/download')

I can check from response.status_codeand get the status code = 200. But how do I try/catchfor a specific error, in this case, I want to be able to detect 503 errorand handle them appropriately.

我可以从检查response.status_code并获得status code = 200。但是我如何try/catch针对特定错误,在这种情况下,我希望能够503 error适当地检测和处理它们。

How do I do that?

我怎么做?

采纳答案by Martin Konecny

Why not do

为什么不做

class MyException(Exception);
   def __init__(self, error_code, error_msg):
       self.error_code = error_code
       self.error_msg = error_msg

import requests
s = requests.Session()
response = s.get('http://mycustomserver.org/download')

if response.status_code == 503:
    raise MyException(503, "503 error code")

Edit:

编辑:

It seems that requests library will also raise an Exception for you using response.raise_for_status()

似乎请求库也会为您引发异常使用 response.raise_for_status()

>>> import requests
>>> requests.get('https://google.com/admin')
<Response [404]>
>>> response = requests.get('https://google.com/admin')
>>> response.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 638, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: Not Found

Edit2:

编辑2:

Wrap you raise_for_statuswith the following try/except

raise_for_status用以下内容包裹你try/except

try:
    if response.status_code == 503:
        response.raise_for_status()
except requests.exceptions.HTTPError as e: 
    if e.response.status_code == 503:
        #handle your 503 specific error

回答by K DawG

You might as well do this:

你也可以这样做:

try:
    s = requests.Session()
    response = requests.get('http://mycustomserver.org/download')
    if response.status_code == 503:
        response.raise_for_status()
except requests.exceptions.HTTPError:
    print "oops something unexpected happened!"

response.raise_for_status()raises a requests.exceptions.HTTPErrorand here we are only calling response.raise_for_status()if the status code is equal to 503

response.raise_for_status()引发 a requests.exceptions.HTTPError,这里我们只response.raise_for_status()在状态码等于 503 时调用