python requests報Max retries exceeded with url異常

項目中有個模塊是定時獲取設備狀態的,經過設備的http請求訪問獲取返回的狀態碼,而後根據狀態碼檢測設備是否在線。可是最近發現鏈接後出現了偶爾鏈接不上的狀況,報錯以下:python

2018-06-14 15:51:42,076 - configuration_model - ERROR - HTTPSConnectionPool(host='10.1.1.1', port=443): Max retries exceeded with url: /api/1.0/device/status (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f1393d6fbd0>, 'Connection to 10.1.1.1 timed out. (connect timeout=2)')) 2018-06-14 15:51:48,475 - configuration_model - ERROR - HTTPSConnectionPool(host='10.1.1.1', port=443): Max retries exceeded with url: /api/1.0/device/status (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f2502bfbad0>, 'Connection to 10.1.1.1 timed out. (connect timeout=2)')) 2018-06-14 15:51:55,003 - configuration_model - ERROR - HTTPSConnectionPool(host='10.1.1.1', port=443): Max retries exceeded with url: /api/1.0/device/status (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f1393d6f850>, 'Connection to 10.1.1.1 timed out. (connect timeout=2)'))

最初懷疑是網絡緣由,寫了個定時腳本,看可否穩定復現這個問題:json

#coding:utf-8

import requests
from requests.auth import HTTPBasicAuth
import json
import time
import logging
import logging.handlers
from mlogging import TimedRotatingFileHandler_MP
logging.captureWarnings(True)

def get_logger(logger_fie = "/home/test/testTacConnect.log"):
    logger = logging.getLogger(logger_fie)
    logger.setLevel(logging.DEBUG)
    filehandle = TimedRotatingFileHandler_MP(logger_fie, 'midnight')
    filehandle.suffix = "%Y-%m-%d"
    filehandle.setLevel(logging.DEBUG)
    consolehandle = logging.StreamHandler()
    consolehandle.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    filehandle.setFormatter(formatter)
    consolehandle.setFormatter(formatter)
    logger.addHandler(filehandle)
    logger.addHandler(consolehandle)
    return logger

def getTacstatus(userName, password, tacip, EXITTIME = 2):
    # 設備請求超時時間,默認爲2秒
    status = "0"
    try:
        url = "https://%s/api/1.0/device/status"%(tacip,)
        req = requests.post(url, auth=HTTPBasicAuth(userName, password), timeout=EXITTIME, verify=False)
        result = json.loads(req.content)
        if result.get(u'code') == 200:
            status = "1"
    except Exception as e:
        logger.error(e)
    return status

if __name__ == '__main__':
    tacip = '10.1.1.1'
    userName = '*****'
    password = '*******'
    logger = get_logger()
    while True:
        status = getTacstatus(userName,password,tacip)
        if status != 1:
            logger.debug(status)
        time.sleep(10)

運行了1個小時以後,異常狀態出現了,request請求報了Max retries exceeded with url。api

看了下網上的相關論壇,發現是http請求鏈接太多沒有關閉形成的,在request對象獲取session,而後設置下狀態,以下:
網絡

sess = requests.session()
sess.keep_alive = False

 

更新了代碼,在測試腳本運行,觀察中。session

相關文章
相關標籤/搜索