Python - AI 助手

Python Requests put() 方法



Python Requests 的`put()`方法用於向指定的URL傳送PUT請求。此方法用於使用提供的資料更新或替換給定URL處的資源。

`put()`方法類似於`requests.post()`,但專門用於替換現有資源,而不是建立新資源。它接受URL、資料、報頭、檔案、身份驗證、超時等引數來定製請求。

此方法返回一個響應物件,其中包含有關請求狀態、報頭和內容的資訊,可以根據應用程式的需求進一步處理。

語法

以下是Python Requests `put()`方法的語法和引數:

requests.get(url, params=None, **kwargs)

引數

以下是Python Requests `put()`方法的引數:

  • url: url是要傳送PUT請求的資源的URL。
  • data(可選): 這是要與PUT請求一起傳送的資料。
  • json(可選): 要在主體中傳送的JSON資料。
  • kwargs(可選): 可以傳遞的可選引數,包括headers、cookies、auth、timeout等。

返回值

此方法返回一個Response物件。

示例1

以下是使用python requests `put()`方法的基本PUT請求的基本示例:

import requests

# Define the URL
url = 'https://httpbin.org/put'

# Define the data to be sent in the request body
data = {'key1': 'value1', 'key2': 'value2'}

# Send the PUT request with the data
response = requests.put(url, json=data)

# Print the response status code
print('Status Code:', response.status_code)

# Print the response content
print('Response Content:', response.text) 

輸出

Status Code: 200
Response Content: {
  "args": {},
----------------
----------------
----------------
},
  "origin": "110.226.149.205",
  "url": "https://httpbin.org/put"
}

示例2

當使用Python中的requests模組傳送PUT請求時,我們可以處理請求過程中可能發生的錯誤。以下示例處理put請求中的錯誤:

import requests

try:
    response = requests.put('https://api.example.com/nonexistent', timeout=5)
    response.raise_for_status()  # Raises an HTTPError if the status code is 4xx, 5xx
except requests.exceptions.HTTPError as err:
    print(f'HTTP error occurred: {err}')
except requests.exceptions.RequestException as err:
    print(f'Request error occurred: {err}') 

輸出

Request error occurred: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /nonexistent (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x000001BC03605890>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)"))

示例3

這是一個使用python requests `put()`方法設定超時的PUT請求示例:

import requests

# Define the URL
url = 'https://httpbin.org/put'

# Define the data to be sent in the request body
data = {'key1': 'value1', 'key2': 'value2'}

# Set the timeout for the request (in seconds)
timeout = 5

try:
    # Send the PUT request with the data and timeout
    response = requests.put(url, json=data, timeout=timeout)

    # Print the response status code
    print('Status Code:', response.status_code)

    # Print the response content
    print('Response Content:', response.text)

except requests.Timeout:
    # Handle timeout error
    print('Timeout Error: Request timed out.')

except requests.RequestException as e:
    # Handle other request exceptions
    print('Request Exception:', e)

輸出

Status Code: 200
Response Content: {
  "args": {},
-------------------
-------------------
-------------------
 },
  "origin": "110.226.149.205",
  "url": "https://httpbin.org/put"
}
python_modules.htm
廣告