简体   繁体   中英

Using Python requests to POST to a cgi script

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM