📜  PUT 方法 - Python请求

📅  最后修改于: 2022-05-13 01:54:38.258000             🧑  作者: Mango

PUT 方法 - Python请求

请求库是Python向指定 URL 发出 HTTP 请求的重要方面之一。本文围绕如何使用requests.put()方法向指定的 URL 发出 PUT 请求。在查看 PUT 方法之前,让我们先弄清楚什么是 Http PUT 请求——

PUT Http 方法

PUT 是万维网使用的 HTTP 支持的请求方法。 PUT 方法请求将封闭的实体存储在提供的 URI 下。如果 URI 引用一个已经存在的资源,它会被修改,如果 URI 不指向一个现有资源,那么服务器可以使用该 URI 创建资源。

如何通过Python Requests 发出 PUT 请求

Python 的 requests 模块提供了名为put()的内置方法,用于向指定的 URI 发出 PUT 请求。
句法 -

requests.put(url, params={key: value}, args)

例子 -
出于示例目的,让我们尝试向 httpbin 的 API 发出请求。

Python3
import requests
 
# Making a PUT request
r = requests.put('https://httpbin.org / put', data ={'key':'value'})
 
# check status code for response received
# success code - 200
print(r)
 
# print content of request
print(r.content)


将此文件保存为 request.py 并通过终端运行,

python request.py

输出 -

put-request-pytohn 请求

PUT 和 POST 方法之间的区别

PUTPOST

PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). 
Example – 
 

PUT /article/{article-id}

 

POST method is used to request that the origin server accept the entity enclosed in the 
request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. 
Example – 
 

POST /articles

 

PUT method is idempotent. So if you send retry a request multiple times, that should be equivalent to single request modification.POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.
Use PUT when you want to modify a single resource which is already a part of resources collection. PUT overwrites the resource in its entirety. Use PATCH if request updates part of the resource. 
 
Use POST when you want to add a child resource under resources collection.
Generally, in practice, always use PUT for UPDATE operations.Always use POST for CREATE operations.