python - 使用 Python 请求 POST 到 cgi 脚本

标签 python python-requests httplib

我目前正在使用 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

关于python - 使用 Python 请求 POST 到 cgi 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388017/

相关文章:

python - 错误 : can't start new thread

python - 我怎样才能正确设置这个变量? - Python

python - 在Python SQLAlchemy模型中,为什么有些属性被初始化两次?

python - 有没有一种方法可以在Python中以自定义方式对自定义对象进行排序?

python - 使用 urllib2+httplib.debuglevel 调试连​​接有时不显示调试信息

Python:httplib getresponse 发出许多 recv() 调用

javascript - 单击 html 按钮时使用 javascript 将 json 数据发送到托管的 python Flask api,并在 HTML 标签上打印 API 的响应

python - 使用请求和 BeautifulSoup 下载文件

python - 为什么 Beautifulsoup 找不到这个输入的名称?

python - 线程减慢响应时间 - python