requests庫之請求異常處理


利用requests發出請求時可能會發生異常,requests中有一個exception庫用來區分這些異常。

http協議是基於tcp/ip協議的,tcp/ip三次握手,因此可以在請求中定義等待時間,超出等待時間仍未到達則請求失敗。如requests.get(url,timeout=(3,7)),requests.get(url,timeout=10)

import json
import requests
from requests import exceptions

URL = 'https://api.github.com'

#構建uri
def build_uri(endpoint):
    return '/'.join([URL,endpoint])

def timeout_request():
    try:
        response = requests.get(build_uri('user/emails'),timeout=5)
        response.raise_for_status()
    except exceptions.Timeout as e:
        print(e)
    except exceptions.HTTPError as e:
        print(e)

if __name__=='__main__':
    timeout_request()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM