Sending a POST request

A POST request allows us to send data over to the server which it can then process as it needs to. It is a common method for saving or updating data that is stored in a database on the server machine.

Let's try this out now; open up your server and add a new endpoint as follows:

from flask import Flask, jsonify, request
...
@app.route("/send_me_data", methods=["POST"])
def send_me_data():
data = request.form
for key, value in data.items():
print("received", key, "with value", value)

return "Thanks"
...

This function includes a second argument in the route decorator called methods.  This argument specifies the HTTP methods, which are allowed to be sent to this endpoint. Since we want to send data using a POST request, we set this value to a list containing just the string  POST.

To access the data sent over a POST request, the request object itself must be first imported from the flask module. flask module then provides an ImmutableDict class which can be found in the request.form object. We can loop over this dictionary and do whatever we need to do with its data. In this case, we just print everything received to the command-line window.

To ensure the requester receives a response, we return the string Thanks.

Now, let's adjust our requesting script to use this new endpoint:

import requests

data = {
"pens": 12,
"pencils": "eight",
}

r = requests.post("http://127.0.0.1:5000/send_me_data", data=data)
print(r.text)

We now create some data in our script and use the post method of the requests module to send this to our new endpoint. The data argument of this method is a dictionary of data to send over.

Since our endpoint is no longer returning JSON, we can print r.text to display its response.

Give this script a run and you should see Thanks come back from the server:

> python3 demo/req.py 
Thanks

If you then check on your server, you should see, amongst some of the normal output of flask, that the data that was sent over has also been printed:

 Restarting with inotify reloader
* Debugger is active!
* Debugger PIN: 232-123-067
received pens with value 12
received pencils with value eight
127.0.0.1 - - [27/Feb/2018 16:39:47] "POST /send_me_data HTTP/1.1" 200 -

This means that our sending of data from the requester to the server was successful!

That's the basics of sending and receiving data over HTTP covered. It's now time to make some of the data meaningful and introduce some form of permanent storage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset