Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 511
Idan S Avatar asked Jun 28 '16 07:06

Idan S


People also ask

How do you send and receive HTTP requests in Python?

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.

How do I send a HTTP POST request in Python?

The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.

What Python library would you use to serve HTTP requests?

In this article, you will learn about the Python Requests library, which allows you to send HTTP requests in Python.


1 Answers

For the client side, as a built-in option you'd use urllib.request module. For an even higher-level client, try 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.

like image 188
Artemis Avatar answered Oct 02 '22 20:10

Artemis