request.HTTPError在request.get()404响应后未捕获 [英] requests.HTTPError uncaught after a requests.get() 404 response

查看:134
本文介绍了request.HTTPError在request.get()404响应后未捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在请求库中有一个小问题。



例如,我在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')

在[11]中:resp
输出[11]:<响应[ 503]>

在[12]中:resp.raise_for_status()
...
HTTPError:503服务器错误:服务不可用
pre>

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 not 200:

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屋!

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