首页 > 解决方案 > Flask:向开发服务器发出 POST 请求

问题描述

我可以使用flask run命令行在本地机器上运行 Flask 应用程序/API。这将设置一个本地服务器(对我来说, at http://127.0.0.1:5000/),并在该地址运行应用程序。

完成此操作后,我只需http://127.0.0.1:5000/<route>在浏览器中访问即可向我的应用程序发出 GET 请求。如何向应用程序发出 POST 请求?我还有一些参数要包含在 POST 请求的正文中。

标签: pythonhttpflaskposthttp-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(但有时无法正确执行)


推荐阅读