Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python请求发布到cgi脚本_Python_Python Requests_Httplib - Fatal编程技术网

使用Python请求发布到cgi脚本

使用Python请求发布到cgi脚本,python,python-requests,httplib,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", "Acce

我目前正在使用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库很旧,我想使用较新的请求。如何重构代码以使用请求?我一直在网上寻找一个示例,但找不到任何示例。

您可以在此处使用
请求,方法是将参数作为字典提供,并将编码工作留给库:

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

“我想使用请求”是什么意思?顺便说一句,您所做的是完全合理的,而且是有效的:请注意不要仅仅因为“它较新”(例如CGI像乌龟一样古老)而想要更改到另一个库。
请求
使用
urlib3
,它构建在
httplib
之上
requests
为您提供了一个更有用的API,但您不应该仅仅因为它更新就使用它。.
params
是如何编码的?对于
请求
您不需要手动将参数编码到
应用程序/x-www-form-urlencoded
表单。