python - 尝试/除了使用 Python requests 模块的正确方法?

标签 python exception python-requests request

try:
    r = requests.get(url, params={'s': thing})
except requests.ConnectionError, e:
    print(e)

这是正确的吗?有没有更好的方法来构建它?这会覆盖我所有的基地吗?

最佳答案

查看请求 exception docs 。简而言之:

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

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

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

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

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

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

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

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

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

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

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 指出的那样:

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 - 尝试/除了使用 Python requests 模块的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16511337/

相关文章:

javascript - 如何创建多选以显示 Django 中每个选定内容的详细信息?

C++ try catch 不适用于超出范围的数组

python - 如何为包含整数的列表提取字符串?

python 缩短嵌入的 try-except block

python-3.x - 如何用BeautifulSoup4解析表格并优雅打印?

python - For 循环在 matplotlib 中绘制零 [Python]

python - 如何检查数据库中是否创建了用户并将其删除

python - 来自字符串和变量值组合的字典键名

python - Python异常语法错误

java - 一个类中的应用程序异常作为 EJBTransactionRollbackException 返回到调用类