• python接口自动化(二十八) requests超时重试方法(由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败)


    前言

    “由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败”,这是经常遇到的问题requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))
    一般出现这个问题的原因是:host='www.github.com' 主机地址没连上,使用 requests 发请求时,有些网站服务器不稳定,特别是国外的网站,经常会出现连接失败情况。
    连接失败后,有时候会抛出上面异常,有时候会一直卡住,进入假死状态,没响应,也不会结束。

    timeout

     requests发请求的时候有个默认的超时时间,这个时间在20秒左右

    import requests
    s=requests.session()
    url="https://www.github.com/"
    r=s.request("GET",url=url)
    print(r.text)
    

     连不上服务器会出现异常:requests.exceptions.ConnectionError

    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000020F06524AC8>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))
    

     如果请求一直没响应,进入假死状态,可以加个timeout超时时间,达到这个请求超时时间就结束,如0.1s超时

    import requests
    s=requests.session()
    url="https://www.github.com/"
    r=s.request("GET",url=url,timeout=0.1)
    print(r.text)
    

     这样抛出的异常是:requests.exceptions.ConnectTimeout

     raise ConnectTimeout(e, request=request)
    requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='www.github.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003472358>, 'Connection to www.github.com timed out. (connect timeout=0.1)'))
    

     失败重试 max_retries

     Requests自带了一个传输适配器,也就是HTTPAdapter。这个适配器使用了强大的urllib3, 为Requests提供了默认的HTTP和HTTPS交互。

    每当Session被初始化,就会有适配器附着在Session上,其中一个供HTTP使用,另一个供HTTPS使用。

    import requests
    from requests.adapters import HTTPAdapter
    s=requests.session()
    
    s.mount('http://',HTTPAdapter(max_retries=3))#重试3次
    s.mount('https://',HTTPAdapter(max_retries=3))
    
    url="https://www.github.com/"
    r=s.request("GET",url=url,timeout=0.1)
    print(r.text)
    

     这样每次请求超过0.1s,超过时,会重试3次,最大请求时长0.1s 

     

    越努力,越幸运!!! good good study,day day up!!!
  • 相关阅读:
    Android 节日短信送祝福(UI篇:3-选择短信与发送短信的Activity的实现)
    Android 节日短信送祝福(功能篇:2-短信历史记录Fragment的编写)
    Android 节日短信送祝福(功能篇:1-数据库操作类与自定义ContentProvider)
    Android AIDL 小结
    Android 异步更新UI-线程池-Future-Handler实例分析
    Android 利用线程运行栈StackTraceElement设计Android日志模块
    Android OkHttp网络连接封装工具类
    Android OKHttp源码解析
    Android开发人员不得不收集的代码(持续更新中)
    Android 为开发者准备的最佳 Android 函数库(2016 年版)
  • 原文地址:https://www.cnblogs.com/canglongdao/p/13454007.html
Copyright © 2020-2023  润新知