1. 程式人生 > >requests庫之請求異常處理

requests庫之請求異常處理

git pri name requests poi mail esp ons https

利用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()

requests庫之請求異常處理