How to send and receive HTTP POST requests in Python [closed]

﹥>﹥吖頭↗ 提交于 2019-11-27 14:51:01

问题


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.

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

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


回答1:


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.

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

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

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:

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.



来源:https://stackoverflow.com/questions/38070373/how-to-send-and-receive-http-post-requests-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!