[英]Using Python requests to POST to a cgi script
我目前正在使用python庫httplib將POST請求傳遞給cgi腳本。
# 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
但是,httplib庫很舊,我想使用較新的請求。 如何重構代碼以使用請求? 我一直在網上尋找示例,但找不到任何示例。
您可以在此處使用requests
,方法是將參數作為字典提供,並將編碼工作留給庫:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.