处理 POST、PUT、PATCH 和 DELETE 请求



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

使用 POST

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

import requests

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

输出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"[email protected]"},
"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":"[email protected]"},
"url":"https://postman-echo.com/post"}

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

使用 PUT

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

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

输出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"[email protected]"},
"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":"[email protected]"},
"url":"https://postman-echo.com/put"}

使用 PATCH

对于 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

对于 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"}
广告