Python requests库异常处理

8 投票
2 回答
26257 浏览
提问于 2025-04-18 09:54

我正在使用 Python 的 requests 库创建一个下载服务(可以在这里查看相关文档),目的是从另一个服务器下载数据。问题是,有时候我会遇到 503 错误,这时我需要显示一个合适的提示信息。下面是一些示例代码:

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

我可以通过 response.status_code 来检查状态,并且可以得到 状态码 = 200。但我该如何使用 try/catch 来处理特定的错误呢?在这种情况下,我想能够检测到 503 错误 并进行相应的处理。

我该怎么做呢?

2 个回答

4

你可以这样做:

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() 这个命令会抛出一个 requests.exceptions.HTTPError 错误,而我们这里只在状态码等于 503 的时候才会调用 response.raise_for_status()

15

为什么不这样做呢

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")

补充:

看起来,requests库在你使用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

补充2:

把你的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

撰写回答