通过HTTPAdapter使用会话时,Python请求不引发异常

时间:2019-06-06 18:11:11

标签: python python-requests

我使用python监视在服务上创建的多个动态DNS条目,但是由于某种原因,一个主机macmillan.dynamix.pro导致脚本无限期冻结。

以下代码使用请求标头方法获取状态代码。第一个try catch块不使用Retry()对象,并且按预期引发异常。但是,第二个try catch块不会引发异常,并且脚本使用从def requests_retry_session

创建的requests.Session()对象无限期冻结。
############################
#  Imports                 #
############################

from urlparse import urlparse
from threading import Thread
from Queue import Queue
import httplib
import re
import urllib2
import socket
import requests # sudo pip install requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

# Below comes from https://www.peterbe.com/plog/best-practice-with-retries-with-requests
def requests_retry_session(
        retries=0,
        backoff_factor=1,
        status_forcelist=(500, 502, 504),
        session=None,
):
        session = session or requests.Session()
        retry = Retry(
                total=None,
                read=retries,
                connect=retries,
                backoff_factor=backoff_factor,
                status=retries,
                status_forcelist=status_forcelist,
        )
        adapter = HTTPAdapter(max_retries=retry)
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        return session

try:
        urlResp = requests.head("https://macmillan.dynamix.pro", timeout=(3, 3), verify=False)
        status = str(urlResp.status_code)
        print "Status is " + status
except Exception as e:
        print "bad " + str(e)

try:
        urlResp = requests_retry_session().head("https://macmillan.dynamix.pro", timeout=(3, 3), verify=False)
        status = str(urlResp.status_code)
        print "Status is " + status
except Exception as e:
        print "bad " + str(e)

有人知道为什么会这样吗?

0 个答案:

没有答案