乐闻世界logo
搜索文章和话题

Is there any way to do HTTP PUT request in Python?

1个答案

1

First, ensure that the requests library is installed. If not installed, you can install it by running the following command:

bash
pip install requests

After installation, you can use the following code to perform an HTTP PUT request:

python
import requests url = 'http://example.com/api/resource' data = { 'key1': 'value1', 'key2': 'value2' } response = requests.put(url, json=data) print(response.status_code) print(response.json())

In this example, we first import the requests library, define the request URL and data payload, and then use the requests.put method to send the PUT request with the data formatted as JSON. After executing the request, we print the response status code and parsed JSON content.

This approach is ideal for scenarios requiring modification or updates to server-side resources. For instance, when developing a web application that needs to update user information on the server, you can leverage the PUT request to accomplish this.

Additionally, while the http.client module in Python's standard library or third-party libraries like httpx can perform similar operations, the requests library is widely preferred due to its simplicity, readability, and ease of use.

2024年8月5日 01:03 回复

你的答案