Python - AI 助手

Python Requests options() 方法



Python Requests 的 options() 方法用於向指定的 URL 傳送 OPTIONS 請求。OPTIONS 請求用於描述目標資源的通訊選項,通常用於檢索允許的 HTTP 方法,例如 GET、POST、PUT、DELETE 等,這些方法可以用於訪問資源。

此方法通常用於 CORS(跨源資源共享)中的預檢請求,以檢查在跨不同域訪問資源時允許使用哪些方法和標頭。此方法返回一個響應物件,其中包含狀態程式碼和標頭,但不包含主體內容。

語法

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

requests.options()

引數

此引數不接受任何引數。

返回值

此方法返回一個 Response 物件。

示例 1

以下是使用 Python Requests options() 方法傳送 OPTIONS 請求的基本示例:

import requests

# Define the URL
url = 'https://www.google.com'

# Send the OPTIONS request
response = requests.options(url)

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

# Print the response headers
print('Response Headers:', response.headers)

輸出

Status Code: 405
Response Headers: {'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1592', 'Date': 'Mon, 24 Jun 2024 11:06:13 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}

示例 2

Python Requests 的 options() 方法通常不會像 POST 或 PUT 請求那樣在主體中包含請求引數。相反,引數通常可以透過 URL 作為查詢引數傳遞。

以下是如何使用 Python 中的 requests 模組傳送帶有引數的 OPTIONS 請求:

import requests

params = {'key': 'value'}
response = requests.options('https://www.google.com/options-endpoint', params=params)
print(response.url)
print(response.headers)

輸出

https://www.google.com/options-endpoint?key=value
{'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1577', 'Date': 'Mon, 24 Jun 2024 11:13:48 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}

示例 3

我們可以使用 requests.options() 方法的 cookies 引數,將 cookie 與 OPTIONS 請求一起傳送。以下是一個示例:

import requests

# Define the URL
url = 'https://www.google.com'

# Send the OPTIONS request
response = requests.options(url)

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

# Print the response headers
print('Response Headers:', response.headers)

輸出

Status Code: 405
Response Headers: {'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1592', 'Date': 'Mon, 24 Jun 2024 11:06:13 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}
python_modules.htm
廣告