处理 POST、PUT、PATCH 和 DELETE 请求


在本章中,我们将了解如何使用 requests 库使用 POST 方法以及如何将参数传递给 URL。

使用POST

对于 PUT 请求,Requests 库有 requests.post() 方法,其示例如下所示 -

导入请求

myurl = 'https://postman-echo.com/post'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.post(myurl, data=myparams)
print(res.text)

输出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":"30","accept":"*/*","accept-encoding":"gzip,deflate","content-
type":"application/x-www-form-urlencoded","user-agent":"python-
requests/2.22.0","x-forwarded-
port":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},
"url":"https://postman-echo.com/post"}

在上面显示的示例中,您可以将表单数据作为键值对传递给 requests.post() 内的数据参数。我们还将了解如何在请求模块中使用 PUT、PATCH 和 DELETE。

使用 PUT

对于 PUT 请求,Requests 库有 requests.put() 方法,其示例如下所示。

import requests
myurl = 'https://postman-echo.com/put'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.put(myurl, data=myparams)
print(res.text)

输出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":
"30","accept":"*/*","accept-encoding":"gzip, deflate","content-
type":"applicatio
n/x-www-form-urlencoded","user-agent":"python-requests/2.22.0","x-forwarded-
port
":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},
"url":"https://postman-echo.com/put"}

使用补丁

对于 PATCH 请求,Requests 库有 requests.patch() 方法,其示例如下所示。

import requests
myurl = https://postman-echo.com/patch'
res = requests.patch(myurl, data="testing patch")
print(res.text)

输出

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"13","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/patch"}

使用删除

对于DELETE请求,Requests库有requests.delete()方法,其示例如下所示。

import requests
myurl = 'https://postman-echo.com/delete'
res = requests.delete(myurl, data="testing delete")
print(res.text)

输出

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"14","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/delete"}