Handling forms with requests

Typically, you want to send some form-encoded data. To do this, simply pass a dictionary to the data argument. Your data dictionary will automatically be form-encoded when the request is made. The requests library takes care of all the encoding and formatting for us.

In this example, we are going to simulate the sending of an HTML form through a POST request, just like browsers do when we send a form to a website. Form data is always sent in key-value dictionary format.

The request.post() function sends a request using the PUT method with the following syntax:

requests.post ('<URL>', data = <object>, json = <object type dict>)

You can find the following code in the form_post_method.py file: 

import requests

data_dictionary = {'custname': 'customer','custtel': '323232',
'size': 'large','custemail': '[email protected]'}
response = requests.post("http://httpbin.org/post",data=data_dictionary)
# we then print out the http status_code
print("HTTP Status Code: " + str(response.status_code))
if response.status_code == 200:
print(response.text)

In this screenshot, we can see the execution of the previous script:

In the script response, we see how the information appears, that is being sent in the request data dictionary object in the form section data.

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

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