request.HTTPError在request.get()404响应后未捕获 [英] requests.HTTPError uncaught after a requests.get() 404 response
问题描述
我在请求库中有一个小问题。
例如,我在Python中有一个这样的陈述:
try:
request = requests.get('google.com/admin')#Should返回404
除了请求.HTTPError,e:
打印'HTTP错误%s发生'%e.code
由于某些原因,该异常未被捕获。我已经检查了API文档的请求,但有点苗条。有没有谁有更多的经验可以帮助我的图书馆?
口译是你的朋友:
import request
requests.get('google.com/admin')
#MissingSchema:无效的URL u'google.com / admin':没有提供模式
另外,请求
例外:
import requests.exceptions
dir(requests.exceptions)
还要注意,默认情况下请求
不会引发异常,如果状态不是 200
:
在[9]中:requests.get('https://google.com/admin')
出[9]:<响应[503]>
有 raise_for_status()方法:
在[10]中:resp = requests.get('https://google.com/admin')
pre>
在[11]中:resp
输出[11]:<响应[ 503]>
在[12]中:resp.raise_for_status()
...
HTTPError:503服务器错误:服务不可用
I'm having a slight problem with the requests library.
Say for example I have a statement like this in Python:
try: request = requests.get('google.com/admin') #Should return 404 except requests.HTTPError, e: print 'HTTP ERROR %s occured' % e.code
For some reason the exception is not being caught. I've checked the API documentation for requests but it's a bit slim. Is there anyone who has more experience with the library that might be able to help me out?
解决方案Interpreter is your friend:
import requests requests.get('google.com/admin') # MissingSchema: Invalid URL u'google.com/admin': No schema supplied
Also,
requests
exceptions:import requests.exceptions dir(requests.exceptions)
Also notice that by default
requests
doesn't raise exception if status is not200
:In [9]: requests.get('https://google.com/admin') Out[9]: <Response [503]>
There is raise_for_status() method that does it:
In [10]: resp = requests.get('https://google.com/admin') In [11]: resp Out[11]: <Response [503]> In [12]: resp.raise_for_status() ... HTTPError: 503 Server Error: Service Unavailable
这篇关于request.HTTPError在request.get()404响应后未捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!