2017-08-05 18 views
0

我的網絡應用程序請求多個URL,並且有時會引發SSL證書錯誤。他們都是第三方網址,所以我無法修復他們的錯誤,我不想登錄他們。不過,有些東西是自己記錄下來的:2017-08-05 00:22:49,496 ERROR -- : Certificate did not match expected hostname: www.improving-autonomy.org. Certificate: {'subjectAltName': [('DNS', '*.wordpress.com'), ('DNS', 'wordpress.com')], 'subject': ((('commonName', u'*.wordpress.com'),),)}任何人都知道我該如何阻止它?請找到我的代碼波紋管。提前謝謝了!不記錄'證書與預期的主機名不符'錯誤消息

try : 
    ua = UserAgent() 
    headers = {'Content-Type' : 'text/html', 'Accept-Encoding' : None, 'User-Agent' : ua.random} 
    response = requests.get(url, headers=headers, timeout=10) 
except ssl.CertificateError as e : 
    pass 

更新 - : 看起來請求模塊的日誌它(connection.py)。如果我已經捕捉到相同的異常,爲什麼它會繼續記錄?

def _match_hostname(cert, asserted_hostname): 
    try: 
     match_hostname(cert, asserted_hostname) 
    except CertificateError as e: 
     log.error(
      'Certificate did not match expected hostname: %s. ' 
      'Certificate: %s', asserted_hostname, cert 
     ) 
    # Add cert to exception and reraise so client code can inspect 
    # the cert when catching the exception, if they want to 
    e._peer_cert = cert 
    raise 
+0

您是否嘗試通過調試器來查看日誌實際發生的位置?它看起來像也許有檢查錯誤,發現錯誤,日誌被創建,然後引發異常。需要通過追蹤代碼來驗證。 – idjaw

+0

它發生在請求模塊中。 connection.py文件 –

+0

任何想法?我已經遇到了同樣的例外。爲什麼它自己記錄? –

回答

2

當然。你捕獲同樣的例外,但你沒有看到的是其中這種情況正在發生。讓我們來看看什麼樣的片段發生在這裏:

except CertificateError as e: 
    log.error(
     'Certificate did not match expected hostname: %s. ' 
     'Certificate: %s', asserted_hostname, cert 
    ) 
# Add cert to exception and reraise so client code can inspect 
# the cert when catching the exception, if they want to 
e._peer_cert = cert 
raise 

所以,當第一次拋出的異常,該代碼捕獲CertificateError,那麼它使log.error,該證書指定爲一個屬性,每在代碼中發表評論,然後致電raise

那空raise呼叫現在要再次加註的最後一次例外,這CertificateError例外,那你趕上什麼。所以日誌調用已經由該代碼完成,並且您正在從該特定的調用中調用異常捕獲。

+0

我看到...有無論如何避免這第一個日誌? –

+1

你可以玩弄我相信那些模塊的日誌級別。看看[這](https://stackoverflow.com/questions/11029717/how-do-i-disable-log-messages-from-the-requests-library)回答這方面的一些信息,看看它是否可以幫助你。 – idjaw

+0

我在這裏寫的工作代碼:'logging.getLogger(「requests.packages.urllib3」).setLevel(logging.CRITICAL)' –

0

您可以捕獲該異常並打印的類型:

except Exception as exc: 
    print exc, exc.message, exc.__class__ 

然後在你的代碼中使用此特定的異常類型,它應該工作。您也可以在except語句後面添加else子句,並將日誌代碼放在那裏。只有當try塊執行成功時纔會執行此代碼

+0

請求模塊記錄它捕捉'CertificateError' –

相關問題