将此curl cmd转换为Python 3

将此curl cmd转换为Python 3,第1张

概述以下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 如何以正确的 以下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 requestsurl = '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 b64encodefrom urllib.parse import urlencodefrom urllib.request import Request,urlopenuser,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.pemresponse = urlopen(Request(url,data,headers),cafile=cafile)print(response.info())print(response.read().decode()) # assume utf-8 (likely for application/Json)
总结

以上是内存溢出为你收集整理的将此curl cmd转换为Python 3全部内容,希望文章能够帮你解决将此curl cmd转换为Python 3所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/1048024.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存