python - Flask:向开发服务器发出 POST 请求
问题描述
我可以使用flask run
命令行在本地机器上运行 Flask 应用程序/API。这将设置一个本地服务器(对我来说, at http://127.0.0.1:5000/
),并在该地址运行应用程序。
完成此操作后,我只需http://127.0.0.1:5000/<route>
在浏览器中访问即可向我的应用程序发出 GET 请求。如何向应用程序发出 POST 请求?我还有一些参数要包含在 POST 请求的正文中。
解决方案
您无法在浏览器中POST
使用请求。URL
它需要HTML
具有
<form method="POST">
</form>
这样您的服务器就会将此页面发送给您。
除了浏览器之外,您还可以使用 Python 模块,例如可以运行,等的urllib
或更简单的模块。requests
.get()
.post(...)
在示例中,我使用https://httpbin.org/post,因为它会发回您所获得的所有内容 - 标题、发布数据、cookie 等,因此您可以看到您发送的内容。
import requests
#url = 'http://127.0.0.1:5000'
url = 'https://httpbin.org/post'
# POST/form data
payload = {
'search': 'hello world',
}
r = requests.post(url, data=payload)
print(r.text)
结果:
{
"args": {},
"data": "",
"files": {},
"form": {
"search": "hello world"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Content-Length": "18",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.26.0",
"X-Amzn-Trace-Id": "Root=1-61687ab9-7bae70cf5bfdcbb75524b71b"
},
"json": null,
"origin": "83.11.118.179",
"url": "https://httpbin.org/post"
}
有些人使用邮递员GUI
之类的工具来测试页面 - 它还可以发送请求 POST/GET/DELETE/OPTION/等。
您也可以尝试使用curl等控制台程序
curl https://httpbin.org/post -X POST -d "search=hello world"
{
"args": {},
"data": "",
"files": {},
"form": {
"search": "hello world"
},
"headers": {
"Accept": "*/*",
"Content-Length": "18",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "curl/7.68.0",
"X-Amzn-Trace-Id": "Root=1-61687da3-5eaaa4ff6419c36639a2cc5d"
},
"json": null,
"origin": "83.11.118.179",
"url": "https://httpbin.org/post"
}
顺便提一句:
一些 API 在文档中使用curl作为示例来展示如何使用 API。
有页面https://curl.trillworks.com可以转换curl
为 Python requests
(但有时无法正确执行)
推荐阅读
- java - 如何修改 .PDF 文件,以便将其从在线和离线电子书应用程序中复制出来?
- r - 如何在空间上对物种出现数据的 data.frames 列表进行稀疏化?
- visual-studio - Visual Studio 2019 - 某些配置不会更新平台
- css - React 组件未使用 linaria 进行动画处理
- node.js - 码头工人 npm 安装 ERR
- javascript - 下一个未处理的运行时错误。未找到路由器实例
- java - 如何定义控制器方法以接受具有 Spring Boot 归档的媒体类型的 JSON?
- docker - 在 docker-compose.yml 中添加“extra_hosts”的更好方法
- android - 无法从 android Q 中的 Google Nearby Connections API 访问下载的文件
- python - 如何使我的代码从一行移动到之前发生的另一行?