Sending an HTTP POST Request from a Python Script


import httplib httpServ = httplib.HTTPConnection("testserver.net", 80) httpServ.connect() quote = "Use a Python script to post to the CGI Script." httpServ.request('POST', '/cgi_form.cgi', 'name=Brad&quote=%s' \     % quote)     response = httpServ.getresponse()     if response.status == httplib.OK:     printText (response.read()) httpServ.close()

You also might need to send POST requests directly to a web server from a Python script rather than a web browser. This effectively enables you to write client-side applications without having to deal with the web browser.

The httplib module included with Python provides the classes and functions to connect to a web server, send a POST request, and handle the response without the use of a web browser.

First, create a server connection object by executing the httplib.HTTPConnection(address, port) function, which returns an HTTPServer object. Then connect to the server by calling the connect() function of the HTTPServer object.

To send the POST request, call request(method [, url [, body [, headers). Specify POST as the method of the request. Specify the location of the script to handle the post as the url. Specify the query string that needs to be passed with the POST as the body.

Note

In the sample code, we send a CGI script with parameters. Because the web server executed the CGI script, the response from the server will be the output of the CGI script, not the script itself.


After you have sent the request, get the server's response using the getresponse() function of the HTTPServer object. The getresponse() function returns a response object that acts like a file object, allowing you to read the response using the read() request.

Note

You can check the status of the response by accessing the status attribute of the response object.


import httplib def printText(txt):     lines = txt.split('\n')     for line in lines:         print line.strip() #Connect to server httpServ = httplib.HTTPConnection("testserver.net", 80) httpServ.connect() #Send Get cgi request quote = \ "Use a Python script to post to the CGI Script." httpServ.request('POST', \ '/cgi_form.cgi', 'name=Brad&quote=%s' % quote) #Wait for response response = httpServ.getresponse() if response.status == httplib.OK:     print "Output from CGI request"     print "========================="     printText (response.read()) httpServ.close()


http_post.py

Output from CGI request ========================= <title>CGI Form Response</title> <h2>Current Quote</h2><P> <b>Brad</b>: Use a Python script to post to the CGI Script.


Output from http_post.py code.



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net