Convert this curl cmd to Python 3

The following curl command works fine (private anonymous data):

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 

How can I send this exact HTTPS POST request in the correct Python3.3 path? I don't want to use anything other than the Python 3.3 standard library if I can avoid it (in other words, without using the twilio python module, or β€œqueries”, or pycurl, or anything outside of a simple vanilla-based Python installation 3.3).

The preferred Python approach seems to continue to evolve from version to version, the fragments that I find on Google never mention which version they use or do not complete the registration part, Python documents are full of "deprecated from 3". x "but never include code samples of a new way of doing things ....

If curl can do this so easily, then standard Python 3.3 can. But how exactly should this be done now?

+4
source share
1 answer

Here is a version that works on both Python 2 and 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() 

To make a request to send https with basic HTTP authentication in Python 3.3:

 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) 
+8
source

All Articles