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.

3
  • 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). Commented Oct 15, 2014 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.. Commented Oct 15, 2014 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. Commented Oct 15, 2014 at 17:06

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.