使用Python请求模块的正确方法是什么?

[英]Correct way to try/except using Python requests module?


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?

这是正确的吗?有更好的方法来构建这个结构吗?这能覆盖我所有的基地吗?

2 个解决方案

#1


419  

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

查看一下请求异常文档。简而言之:

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

如果出现网络问题(如DNS失败、拒绝连接等),请求将引发ConnectionError异常。

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

在出现罕见的无效HTTP响应时,请求将引发HTTPError异常。

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.

如果一个请求超过了最大重定向的配置数量,就会引发一个toomany重定向异常。

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

所有请求显式地增加的异常都从request .exception . 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.

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

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, a call to sys.exit() is in order.

当捕获异常时,应该做什么实际上取决于脚本/程序的设计。退出是可以接受的吗?你能再试一次吗?如果错误是灾难性的,并且您不能继续,那么可以调用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
    print e
    sys.exit(1)

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.
    print e
    sys.exit(1)

As Christian pointed out:

基督徒指出:

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.

如果希望http错误(例如,401未授权)引发异常,可以调用Response.raise_for_status。如果响应是http错误,则会引发HTTPError。

An example:

一个例子:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    print err
    sys.exit(1)

Will print:

将打印:

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

#2


18  

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

另外一个需要明确的建议。似乎最好从特定的错误到一般的错误,以获取所需的错误,这样特定的错误就不会被常规错误所掩盖。

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

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

vs

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/05/12/5a46d9a39c0eeff7adc52b8a301ee210.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告