如何在 Python 中发送和接收 HTTP POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38070373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:17:33  来源:igfitidea点击:

How to send and receive HTTP POST requests in Python

pythonhttphttp-posthttplib

提问by Idan S

I need a simple Client-side method that can send a boolean value in a HTTP POST request, and a Server-side function that listens out for, and can save the POST content as a var.

我需要一个简单的客户端方法,它可以在 HTTP POST 请求中发送一个布尔值,以及一个可以侦听并将 POST 内容保存为 var 的服务器端函数。

I am having trouble finding information on how to use the httplib.

我在查找有关如何使用httplib.

Please show me a simple example, using localhost for the http connection.

请给我看一个简单的例子,使用 localhost 进行 http 连接。

回答by Artemis

For the client side, you can do all sorts of requests using this python library: requests. It is quite intuitive and easy to use/install.

对于客户端,您可以使用这个 python 库执行各种请求:requests。它非常直观且易于使用/安装。

For the server side, I'll recommend you to use a small web framework like Flask, Bottleor Tornado. These ones are quite easy to use, and lightweight.

对于服务器端,我建议你使用一个小的 web 框架,比如FlaskBottleTornado。这些都很容易使用,而且很轻。

For example, a small client-side code to send the post variable foousing requests would look like this:

例如,foo使用请求发送 post 变量的小型客户端代码如下所示:

import requests
r = requests.post("http://yoururl/post", data={'foo': 'bar'})
# And done.
print(r.text) # displays the result body.

And a server-side code to receive and use the POST request using flask would look like this:

使用flask接收和使用POST请求的服务器端代码如下所示:

from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def result():
    print(request.form['foo']) # should display 'bar'
    return 'Received !' # response to your request.

This is the simplest & quickest way to send/receive a POST request using python.

这是使用 python 发送/接收 POST 请求的最简单、最快捷的方法。