Curl Alternative in Python

CURL alternative in Python

import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.

Python equivalent of Curl HTTP post

import urllib2

req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()

where data is the encoded data you want to POST.

You can encode a dict using urllib like this:

import urllib

values = { 'foo': 'bar' }
data = urllib.urlencode(values)

What is the python equivalent of curl -x

import requests

headers = {'Accept': 'application/vnd.github.v3+json'}

response = requests.delete(url='https://api.github.com/repos/octocat/hello-world', headers=headers)

-X DELETE is the HTTP method you are using, here we use delete method from requests module

-H is to specify the request headers, here we achieve it with headers parameter

Equivalent python code for curl command for https call

We can do this with requests like this:

import requests
header = {'Authorization': 'bearer <token>'}
resp = requests.get("https://IP:PORT/api/v1/namespaces",
headers = header,
verify=False)
print(resp.status_code)
print(resp.text)
  • The -H switch behaviour is replicated by sending a header
  • The -L switch behaviour is replicated by specifying verify=False
  • The -sS and -k are about the behaviour of curl and not relevant here
  • The -X GET is replicated by using requests.get()


Related Topics



Leave a reply



Submit