- 请求教程
- 请求 - 主页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - Http 请求如何工作?
- 请求 - 处理请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求标头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网页抓取
- 请求有用的资源
- 请求 - 快速指南
- 请求 - 有用的资源
- 请求 - 讨论
处理 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"}