如何使用Python处理POST请求?

2024-05-16 21:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设置一个小的Python 3.8脚本,它可以侦听和处理POST请求。我想听听Trello的帖子,然后记录数据。我阅读的每一个视频或指南都展示了如何处理来自HTML表单的POST请求

特雷罗举例:

{
   "action": {
      "id":"51f9424bcd6e040f3c002412",
      "idMemberCreator":"4fc78a59a885233f4b349bd9",
      "data": {
         "board": {
            "name":"Trello Development",
            "id":"4d5ea62fd76aa1136000000c"
         },
         "card": {
            "idShort":1458,
            "name":"Webhooks",
            "id":"51a79e72dbb7e23c7c003778"
         },
         "voted":true
      },
      "type":"voteOnCard",
      "date":"2013-07-31T16:58:51.949Z",
      "memberCreator": {
         "id":"4fc78a59a885233f4b349bd9",
         "avatarHash":"2da34d23b5f1ac1a20e2a01157bfa9fe",
         "fullName":"Doug Patti",
         "initials":"DP",
         "username":"doug"
      }
   },
   "model": {
      "id":"4d5ea62fd76aa1136000000c",
      "name":"Trello Development",
      "desc":"Trello board used by the Trello team to track work on Trello.  How meta!\n\nThe development of the Trello API is being tracked at https://trello.com/api\n\nThe development of Trello Mobile applications is being tracked at https://trello.com/mobile",
      "closed":false,
      "idOrganization":"4e1452614e4b8698470000e0",
      "pinned":true,
      "url":"https://trello.com/b/nC8QJJoZ/trello-development",
      "prefs": {
         "permissionLevel":"public",
         "voting":"public",
         "comments":"public",
         "invitations":"members",
         "selfJoin":false,
         "cardCovers":true,
         "canBePublic":false,
         "canBeOrg":false,
         "canBePrivate":false,
         "canInvite":true
      },
      "labelNames": {
         "yellow":"Infrastructure",
         "red":"Bug",
         "purple":"Repro'd",
         "orange":"Feature",
         "green":"Mobile",
         "blue":"Verified"
      }
   }
}

Tags: thenamehttpsboardcomidfalsetrue
2条回答

如果您想要监听POST请求,那么您需要某种Web服务器

您可以通过flask、django或任何其他框架使用python获得Web服务器 另一种选择是使用python库“http.server”

https://github.com/hacker1221/python3-server

在这里,我创建了一个简单的Python3HTTP服务器,用于记录所有GET和POST请求

enter image description here

我将研究使用轻量级web应用程序框架,如Flask。使用Flask,您可以用Python创建一个简单的服务器端脚本来侦听POST请求并处理数据

例如:

首先,安装Flask:pip install flask

下面是一个示例脚本:

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def result():
    print(request.data)  # raw data
    print(request.json)  # json (if content-type of application/json is sent with the request)
    print(request.get_json(force=True))  # json (if content-type of application/json is not sent)

Flask包含一个开发服务器,但是要在生产环境中运行它,您应该参考Flask Deployment Options

相关问题 更多 >