将这个curl命令转换为Python 3

2024-04-20 00:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

以下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,或者普通python3.3安装之外的任何东西)。

首选的Python方法似乎在不断地从一个版本发展到另一个版本,我在google上找到的片段从来没有提到他们使用的是哪个版本,也没有做登录部分,Python文档中充满了“自从3.x以来就被弃用了”的内容,但是从来没有包含新方法的代码示例。。。。

如果curl可以这么容易地做到这一点,那么标准Python 3.3也可以。但现在该怎么做呢?


Tags: 数据方法https命令版本comapi标准
1条回答
网友
1楼 · 发布于 2024-04-20 00:48:21

下面是一个在Python2和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 post请求,请执行以下操作:

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)

相关问题 更多 >