python requests.exceptions.ConnectionError
今天遇到一个奇葩问题,
1.r.request.post(url)
2..print r. status_code
居然第一步就报错了,原因是url不正确,按道理应该可以走到第二步然后输入404的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import requests try : requests.get( "http://not.a.real.url/really_not" ) except requests.exceptions.ConnectionError as e: pass >>> e ConnectionError(MaxRetryError( "HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)" ,),) >>> e.args (MaxRetryError( "HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)" ,),) >>> e.args[ 0 ] MaxRetryError( "HTTPConnectionPool(host='not.a.real.url', port=80): Max retries exceeded with url: /really_not (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known)" ,) >>> dir (e.args[ 0 ]) [ '__class__' , '__delattr__' , '__dict__' , '__doc__' , '__format__' , '__getattribute__' , '__getitem__' , '__getslice__' , '__hash__' , '__init__' , '__module__' , '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__setattr__' , '__setstate__' , '__sizeof__' , '__str__' , '__subclasshook__' , '__unicode__' , '__weakref__' , 'args' , 'message' , 'pool' , 'reason' , 'url' ] >>> e.args[ 0 ].reason gaierror( - 2 , 'Name or service not known' ) >>> dir (e.args[ 0 ].reason) [ '__class__' , '__delattr__' , '__dict__' , '__doc__' , '__format__' , '__getattribute__' , '__getitem__' , '__getslice__' , '__hash__' , '__init__' , '__module__' , '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__setattr__' , '__setstate__' , '__sizeof__' , '__str__' , '__subclasshook__' , '__unicode__' , '__weakref__' , 'args' , 'errno' , 'filename' , 'message' , 'strerror' ] >>> e.args[ 0 ].reason.errno - 2 |
这样就可以异常设置值
1 2 3 4 5 6 7 8 | try : r = login_session.post( self .url, data = self .data,headers = self .headers) except requests.exceptions.ConnectionError as e: # print e.args[0].reason #[Errno 11004] getaddrinfo failed if e.args[ 0 ].reason.errno = = 11004 : r = 404 final: return r |
得到r,即使不是response类型,也能获取值
getattr(result, 'status_code', result)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了