加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

将此curl cmd转换为Python 3

发布时间:2020-12-13 19:26:10 所属栏目:Linux 来源:网络整理
导读:以下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方式发送这个
以下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方法似乎不断从版本发展到版本,Googling发现的片段从未提及他们使用的版本或不执行登录部分,Python文档充满了“自3.x以来弃用”但永远不要包含新的做事方式的代码示例….

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

解决方法

这是一个适用于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',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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读