gpt4 book ai didi

python - 尝试/使用Python请求模块的正确方法?

转载 作者:行者123 更新时间:2023-12-03 08:40:30 26 4
gpt4 key购买 nike

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

这个对吗?有没有更好的方法来构造它?这会覆盖我所有的基地吗?

最佳答案

看一下Requests 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请求模块的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61961643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com