【问题标题】:Convert this curl cmd to Python 3将此 curl cmd 转换为 Python 3
【发布时间】:2013-01-01 20:00:37
【问题描述】:

以下 curl 命令完美运行(私有数据匿名):

curl -X POST 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json' \
-d 'From=%2B14155551234' \
-d 'To=%2B17035551212' \
-d 'Body=This+is+a+test' \
-u foo:bar

如何以正确的 Python3.3 方式发送这个完全相同的 HTTPS POST 请求?如果可以避免的话,我不想使用 Python 3.3 标准库以外的任何东西(换句话说,不使用 twilio python 模块,或“请求”,或 pycurl,或普通香草 Python 之外的任何东西3.3 安装)。

首选的 Python 方法似乎不断地从一个版本到另一个版本,我通过谷歌搜索找到的 sn-ps 从未提及他们正在使用哪个版本或不做登录部分,Python 文档充满了“不推荐使用3.x”,但从不包含新的做事方式的代码示例......

如果 curl 可以如此轻松地做到这一点,那么标准 Python 3.3 也可以。但是这个应该现在具体怎么做呢?

【问题讨论】:

    标签: python post curl https python-3.x


    【解决方案1】:

    这是一个适用于 Python 2 和 3 的版本:

    import requests # pip install requests
    
    url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
    r = requests.post(url, dict(
            From='+17035551212',
            To='+17035551212',
            Body='This is a test'), auth=('foo', 'bar'))
    
    print(r.headers)
    print(r.text) # or r.json()
    

    在 Python 3.3 上使用基本 http 身份验证发出 https 发布请求:

    from base64 import b64encode
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen
    
    user, password = 'foo', 'bar'
    url = 'https://api.twilio.com/2010-04-01/Accounts/abc/SMS/Messages.json'
    data = urlencode(dict(From='+17035551212', To='+17035551212', 
                          Body='This is a test')).encode('ascii')
    headers = {'Authorization': b'Basic ' +
            b64encode((user + ':' + password).encode('utf-8'))}
    cafile = 'cacert.pem' # http://curl.haxx.se/ca/cacert.pem
    response = urlopen(Request(url, data, headers), cafile=cafile)
    
    print(response.info())
    print(response.read().decode()) # assume utf-8 (likely for application/json)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 2021-07-08
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多