2

I am currently using the python library httplib to pass POST requests to a cgi script.

# Make web call to CGI script
user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent,
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "text/plain"}
conn = httplib.HTTPConnection(self.host)
conn.request("POST", "/path/cgi_script.py", params, headers)
response = conn.getresponse()
if debug: print response.status, response.reason

However, the httplib library is old, and I would like to uses requests, which is newer. How can I refactor my code to use requests? I have been looking online for an example, but I cannot find any.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Christopher Spears
  • 1,105
  • 15
  • 32
  • What do you mean by "I would like to use requests"? By the way, What you are doing is perfectly reasonable and it is working: beware of wanting to change to another library just because "it is newer" (CGI, for example, is old as a turtle). – Escualo Oct 15 '14 at 17:05
  • `requests` uses `urllib3` which is built on top of `httplib`. `requests` gives you a far more usable API, but you should not use it just because it is newer.. – Martijn Pieters Oct 15 '14 at 17:05
  • And how is `params` encoded? For `requests` you don't need to manually encode parameters to `application/x-www-form-urlencoded` form. – Martijn Pieters Oct 15 '14 at 17:06

1 Answers1

2

You can use requests here by providing the parameters as a dictionary and leaving the work of encoding to the library:

params = {'foo': 'bar', 'spam': 'eggs'}

user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent, "Accept": "text/plain"}
response = requests.post(
    'http://{}/path/cgi_script.py'.format(self.host),
    headers=headers, data=params)
if debug: print response.status_code, response.reason
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343