Requests-event-hooks

提供:Dev Guides
移動先:案内検索

リクエスト-イベントフック

イベントフックを使用して、リクエストされたURLにイベントを追加できます。 以下の例では、応答が利用可能になったときに呼び出されるコールバック関数を追加します。

コールバックを追加するには、以下の例に示すように、フックparamを使用する必要があります-

import requests
def printData(r, *args, **kwargs):
   print(r.url)
   print(r.text)
getdata = requests.get('https://jsonplaceholder.typicode.com/users',
hooks={'response': printData})

出力

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

以下に示すように、複数のコールバック関数を呼び出すこともできます-

import requests
def printRequestedUrl(r, *args, **kwargs):
   print(r.url)
def printData(r, *args, **kwargs):
   print(r.text)
getdata = requests.get('https://jsonplaceholder.typicode.com/users',
hooks = {'response': [printRequestedUrl, printData]})

出力

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]

以下に示すように作成されたセッションにフックを追加することもできます-

import requests
def printData(r, *args, **kwargs):
print(r.text)
s = requests.Session()
s.hooks['response'].append(printData)
s.get('https://jsonplaceholder.typicode.com/users')

出力

E:\prequests>python makeRequest.py
[
   {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "[email protected]",
      "address": {
         "street": "Kulas Light",
         "suite": "Apt. 556",
         "city": "Gwenborough",
         "zipcode": "92998-3874",
         "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
         }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
         "name": "Romaguera-Crona",
         "catchPhrase": "Multi-layered client-server neural-net",
         "bs": "harness real-time e-markets"
      }
   }
]