【问题标题】:Transforming curl command into Python pycurl or requests将 curl 命令转换为 Python pycurl 或 requests
【发布时间】:2016-05-23 21:18:12
【问题描述】:

尝试在 Python 中使用此 curl 命令:

curl -k -X POST --data "action=login&username=user&password=pass" https://localhost:8443

我已经尝试过如下使用pycurl:

import pycurl
c = pycurl.Curl()
c.setopt(pycurl.URL, "https://localhost:8443")
c.setopt(pycurl.POST, 1)
#tried this too
#c.setopt(pycurl.USERPWD, 'user:pass')
c.setopt(c.HTTPHEADER,"action=login&username=user&password=pass" )
c.setopt(c.VERBOSE, True)
c.perform()

我也在请求中尝试过:

import requests


data = 'action=login&username=user&password=pass'

requests.post('https://localhost:8443', data=data)

但它没有用。不知道我错过了什么,有什么建议吗?

【问题讨论】:

    标签: python curl python-requests pycurl


    【解决方案1】:
    import requests
    
    
    data = {'action': 'login', 'username': 'user', 'password': 'pass'}
    
    requests.post('https://localhost:8443', data=data)
    

    【讨论】:

    • 感谢@Danny 和@AyushShanker 的回答!我之前已经尝试过它们,并且我不断收到requests.exceptions.SSLError: bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],) 任何想法?
    • 好吧,您正在使用 https,但在您的 curl 请求中,您使用了 -k 选项,根据 curl --help: -k, --insecure Allow connections to SSL sites without certs (H) 所以在这种情况下,您必须添加 100% 模拟您的呼叫verify=False (像这样:requests.post('https://localhost:8443', data=data, verify=False))跳过 ssl 证书的验证并且没有得到那个错误......但是使用 https 有点毫无意义...... innit? :)
    • 感谢 Danny 成功了,我使用了 data = {'action': 'login', 'username': 'user', 'password': 'pass'} requests.post('https://localhost:8443', data=data, verify=False)
    【解决方案2】:

    这里是请求翻译

    >>> data = 'action=login&username=user&password=pass'
    >>> requests.post('https://localhost:8443', data=data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多