尝试/排除使用 Python requests 模块的正确方法? [英] Correct way to try/except using Python requests module?

查看:67
本文介绍了尝试/排除使用 Python requests 模块的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try:
    r = requests.get(url, params={'s': thing})
except requests.ConnectionError, e:
    print e #should I also sys.exit(1) after this?

这是正确的吗?有没有更好的方法来构造它?这会涵盖我所有的基础吗?

Is this correct? Is there a better way to structure this? Will this cover all my bases?

推荐答案

查看请求 例外文档.简而言之:

Have a look at the Requests exception docs. In short:

如果出现网络问题(例如 DNS 故障、连接被拒绝等),请求将引发 ConnectionError 异常.

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

如果出现罕见的无效 HTTP 响应,请求将引发 HTTPError 异常.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

如果请求超时,则会引发 Timeout 异常.

If a request times out, a Timeout exception is raised.

如果请求超过配置的最大重定向次数,则会引发 TooManyRedirects 异常.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

Requests 显式引发的所有异常都继承自 requests.exceptions.RequestException.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

为了回答您的问题,您展示的内容不会涵盖您的所有基础.您只会捕获与连接相关的错误,而不会捕获超时的错误.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

捕获异常时该怎么办实际上取决于脚本/程序的设计.退出是否可以接受?你能继续再试一次吗?如果错误是灾难性的并且您无法继续,那么可以,您可以通过引发 SystemExit(打印错误和调用 sys.exit 的好方法).

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

您可以捕获基类异常,它将处理所有情况:

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

或者你可以分别捕捉它们并做不同的事情.

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)


正如 Christian 指出的那样:

如果您希望 http 错误(例如 401 Unauthorized)引发异常,您可以调用 Response.raise_for_status.如果响应是 http 错误,这将引发 HTTPError.

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

示例:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

将打印:

404 Client Error: Not Found for url: http://www.google.com/nothere

这篇关于尝试/排除使用 Python requests 模块的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆