HTTPX 允許您向Client注冊(cè)“事件鉤子”,每次發(fā)生特定類型的事件時(shí)都會(huì)調(diào)用這些鉤子。
當(dāng)前有兩個(gè)事件掛接:
request
?- 在請(qǐng)求完全準(zhǔn)備就緒后,但在將其發(fā)送到網(wǎng)絡(luò)之前調(diào)用。已通過(guò)?request
?實(shí)例。response
?- 在從網(wǎng)絡(luò)獲取響應(yīng)之后,但在將其返回給調(diào)用方之前調(diào)用。已通過(guò)?response
?實(shí)例。這允許您安裝客戶端范圍的功能,如日志記錄、監(jiān)視或跟蹤。
def log_request(request):
print(f"Request event hook: {request.method} {request.url} - Waiting for response")
def log_response(response):
request = response.request
print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}")
client = httpx.Client(event_hooks={'request': [log_request], 'response': [log_response]})
您還可以使用這些鉤子來(lái)安裝響應(yīng)處理代碼,例如此示例,該代碼創(chuàng)建一個(gè)?httpx.HTTPStatusError
?始終在 ?4xx
?和 ?5xx
?響應(yīng)時(shí)引發(fā)的client實(shí)例。
def raise_on_4xx_5xx(response):
response.raise_for_status()
client = httpx.Client(event_hooks={'response': [raise_on_4xx_5xx]})
注意
在確定是否應(yīng)讀取響應(yīng)正文之前調(diào)用響應(yīng)事件掛鉤。
如果需要訪問(wèn)事件掛接內(nèi)的響應(yīng)正文,則需要調(diào)用?.response.read()
?,或者AsyncClients的?response.aread()
?。
鉤子也允許修改request和response對(duì)象。
def add_timestamp(request):
request.headers['x-request-timestamp'] = datetime.now(tz=datetime.utc).isoformat()
client = httpx.Client(event_hooks={'request': [add_timestamp]})
事件掛接必須始終設(shè)置為可調(diào)用列表,并且可以為每種類型的事件注冊(cè)多個(gè)事件掛接。
除了能夠在實(shí)例化?Client
?時(shí)設(shè)置事件鉤子之外,還有一個(gè)?.event_hooks
?屬性,允許您檢查和修改已安裝的鉤子。
client = httpx.Client()
client.event_hooks['request'] = [log_request]
client.event_hooks['response'] = [log_response, raise_on_4xx_5xx]
注意
如果您使用的是 HTTPX 的異步支持,那么您需要注意,注冊(cè)到?httpx.AsyncClient
?的掛接必須是異步函數(shù),而不是普通函數(shù)。
更多建議: