Python - AI 助手

Python Requests delete() 方法



Python Requests 的delete()方法用於向指定 URL 傳送 HTTP DELETE 請求。它允許刪除伺服器上的資源。

此方法接受引數,例如 URL、標頭、Cookie、超時、代理和身份驗證憑據,從而可以自定義請求。執行完成後,它將返回一個 Response 物件,其中包含有關請求的資訊,包括狀態程式碼、標頭和響應內容。

此方法簡化了發出 DELETE 請求和處理響應的過程,使其成為與 RESTful API 和 Web 服務互動的寶貴工具。

語法

以下是 Python Requests delete() 方法的語法和引數 -

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

引數

以下是 Python Requests delete() 方法的引數 -

  • url: 這是我們要刪除的資源的 URL。
  • params(字典或位元組,可選): 要在請求的查詢字串中傳送的字典或位元組。
  • kwargs(可選): 可以傳遞的其他引數,包括標頭、Cookie、身份驗證等。

返回值

此方法返回一個 Response 物件。

示例 1

以下是在其中伺服器將接收 DELETE 請求,並且將列印來自伺服器的響應(包括狀態程式碼和任何響應內容)的基本示例,使用 python requests delete() 方法 -

import requests

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

# Send the DELETE request
response = requests.delete(url)

# 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": {},
  "data": "",
-------------
------------
-----------
 },
  "json": null,
  "origin": "110.226.149.205",
  "url": "https://httpbin.org/delete"
}

示例 2

在 HTTP 中,DELETE 請求通常不包含像 POST 或 PUT 請求那樣的主體中的請求引數。相反,它包含通常作為查詢引數透過 URL 傳遞的引數。以下是如何使用delete()方法傳送帶有引數的 DELETE 請求 -

import requests

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

# Define the parameters
params = {'param1': 'value1', 'param2': 'value2'}

# Send the DELETE request with parameters
response = requests.delete(url, params=params)

# 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": {
    "param1": "value1",
    "param2": "value2"
  },
  "data": "",
-------------
------------
-----------
 },
  "json": null,
  "origin": "110.226.149.205",
  "url": "https://httpbin.org/delete?param1=value1¶m2=value2"
}
python_modules.htm
廣告